gpt4 book ai didi

php - 如何使用计算值对数组进行排序,其中其余数据是从 mysql 数据库接收的?

转载 作者:行者123 更新时间:2023-11-29 13:52:40 25 4
gpt4 key购买 nike

我有一个名为 view.htm 的页面,它根据用户分配给金牌、银牌和铜牌的内容以及他们是否选择使用 GDP 或人口来计算分数来显示结果来自view.php。我需要找到一种方法来按计算出的分数对这些结果进行排序,然后将其限制为前 10 名。我的数据是从 mysql 数据库接收的,分数是在 php 页面中计算的。我正在使用 json_encode 对数据进行编码以将其显示在页面上。 $results 是一个二维数组。这就是从 view.php 中回显结果时的样子:

{"gold":"0","silver":"0","bronze":"1","gdp":"20343461030","population":"34385000",  
"country_name":"Afghanistan","score":"0.029082448742184"},{"gold":"0",
"silver":"0","bronze":"0","gdp":"12959563902","population":"3205000",
"country_name":"Albania","score":"0"},{"gold":"1","silver":"0","bronze":"0",
"gdp":"188681000000","population":"35468000","country_name":"Algeria",
"score":"0.14097214390436"}

下面是用于计算分数的 php 代码:

$results = array();

while ($row = $res->fetchRow()){
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];

$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);

$total_medals = ($resGold + $resSilver + $resGold);
$perMillion = $resPopulation/1000000;
$perBillion = $resGdp/1000000000;

$score_pop = (($gold_score + $silver_score + $bronze_score)/$perMillion);
$score_gdp = ($perBillion/($gold_score + $silver_score + $bronze_score + 1));

if($population == 'true'){
$row['score'] = "$score_pop";
array_push($results,$row);
}

else if($gdp == 'true'){
$row['score'] = "$score_gdp";
array_push($results,$row);
}
}

感谢任何帮助。谢谢

最佳答案

您应该能够使用 array_multisort 对结果进行排序-- 但您需要制作一个列表式的分数数组。因此,当您推送结果时,也会推送到新数组。

缩写...本质上是初始化新数组,并且在推送到 $results 的地方,也推送到 $scores

$results = array();
$scores = array();
while ($row = $res->fetchRow()){
/* snipped */
array_push($results,$row);
array_push($scores,$score_pop);
}

array_multisort($scores, SORT_ASC, $results);

还有一个工作示例(我实际测试过)

    $result = array(
array("name" => "guy", "score" => 30),
array("name" => "dude", "score" => 1),
array("name" => "bro", "score" => 20),
);

$scores = array();
foreach ($result as $r) {
array_push($scores,$r['score']);
}

array_multisort($scores,SORT_ASC,$result);

print_r($result);

(我对制表符/空格表示歉意)

关于php - 如何使用计算值对数组进行排序,其中其余数据是从 mysql 数据库接收的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com