-1

我有一个数组,其中包含我的 sql 数据库中的几个变量。

{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},              {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}

我有一个名为 $score 的附加变量,它使用数据库中的信息来计算这个分数。我想知道如何循环并将正确的分数添加到数组中的每个国家/地区。

我的原始代码:

$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);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
4

1 回答 1

0

您的代码将是这样的:

$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
        {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';

$countries_info_new = array();
$countries_info = json_decode($json_data);

foreach($countries_info as $country_info){
   $country_info['score'] = Get_country_score($country_info['country_name']);
   $countries_info_new[]=$country_info;
}

$new_json_data = json_encode($countries_info_new);
于 2013-04-26T18:42:26.687 回答