我将以下字符串转换为json数组。我要做的所有事情都是将具有相同值的id_number
关键字组合在一起,并将amount
加到每个关键字中,并在循环外打印结果值。
$response = '{
"nhif":[
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T20:18:50"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T19:59:14"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:07:34"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:04:27"
},
{
"id_number":"12345678",
"amount":"5",
"date":"2018-09-14T09:04:21"
}
]
}';
$json_response = json_decode($response, true);
//Start NHIF
foreach ($json_response['nhif'] as $nhif) {
echo ''.$nhif{"id_number"}.' '.$nhif{"amount"}.' '.$nhif{"date"}.'<br/>';
}
//END NHIF
我的预期输出是:
#id_number #amount
AA112233 20
12345678 5
有任何解决方法吗?
答案 0 :(得分:2)
您可以使用array_reduce
通过amount
对id_number
值求和:
$sums = array_reduce($json_response['nhif'], function ($c, $i) {
$c[$i['id_number']] = (isset($c[$i['id_number']]) ? $c[$i['id_number']] : 0) + $i['amount'];
return $c;
}, array());
print_r($sums);
输出:
AA112233 20
12345678 5
如果您使用的是PHP7,则此
isset($c[$i['id_number']]) ? $c[$i['id_number']] : 0
可以简化为
$c[$i['id_number']] ?? 0
答案 1 :(得分:0)
您可以使用数组解决此问题
$response = '{
"nhif":[
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T20:18:50"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T19:59:14"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:07:34"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:04:27"
},
{
"id_number":"12345678",
"amount":"5",
"date":"2018-09-14T09:04:21"
}
]
}';
$json_response = json_decode($response, true);
$results = array(); // will map the unique keys with it's sum
//Start NHIF
foreach ($json_response['nhif'] as $nhif) {
if(!isset($results[$nhif['id_number']])) // new key initialized
$results[$nhif['id_number']] = $nhif['amount'];
else
$results[$nhif['id_number']] += $nhif['amount'];
}
//END NHIF
foreach($results as $key => $value) {
echo $key .' '.$value; // printing the result
}
答案 2 :(得分:0)
尝试使用此代码示例,根据解决问题的技巧,还有许多其他方法可以解决此问题。
$response = '{
"nhif":[
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T20:18:50"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T19:59:14"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:07:34"
},
{
"id_number":"AA112233",
"amount":"5",
"date":"2018-09-14T09:04:27"
},
{
"id_number":"12345678",
"amount":"5",
"date":"2018-09-14T09:04:21"
}
]
}';
$data = json_decode($response, true);
usort($data['nhif'], function($a, $b) {
return $b['id_number'] <=> $a['id_number'];
});
//Start NHIF
$amount = 0;
$id_number = null;
foreach($data['nhif'] as $nhif) {
if(($nhif['id_number'] != $id_number) && ($id_number != null)){
echo $id_number. "\t". $amount . "<br />";
$id_number = $nhif['id_number'];
$amount = $nhif['amount'];
}
else{
$id_number = $nhif['id_number'];
$amount = $amount + $nhif['amount'];
}
// echo ''.$nhif{"id_number"}.' '.$nhif{"amount"}.' '.$nhif{"date"}.'<br />';
}
echo $id_number. "\t". $amount . "<br />";
//END NHIF
答案 3 :(得分:0)