问题:
给定一个包含键值对的数组,根据特定列的值对数据进行分组,并对另一列的数据求和。例如,如果您有以下数组:
$array = [ ['name' => 'Bank BRI', 'amount' => 0], ['name' => 'Bank BRI', 'amount' => 0], ['name' => 'Bank BCA', 'amount' => 1412341234], ['name' => 'Bank CIMB Niaga', 'amount' => 532532552], ['name' => 'Bank BRI', 'amount' => 34534534], ['name' => 'Bank CIMB Niaga', 'amount' => 453425243], ['name' => 'Bank BRI', 'amount' => 0], ['name' => 'Bank BNI', 'amount' => 124124], ['name' => 'Bank CIMB Niaga', 'amount' => 352345623], ['name' => 'Bank BCA', 'amount' => 23432423], ['name' => 'Bank Mandiri', 'amount' => 0], ['name' => 'Bank BCA', 'amount' => 0], ['name' => 'Bank BCA', 'amount' => 0], ['name' => 'Bank Permata', 'amount' => 352352353], ];
解决方案:
根据 'name' 列对数据进行分组并对'amount' 列,请按照以下步骤操作:
迭代整个输入数组后,$bankTotals数组将包含以银行名称为键、以总金额为值的分组数据。
以下是实现所需效果的代码输出:
$bankTotals = array(); foreach($array as $amount) { $bankTotals[$amount['name']] += $amount['amount']; } print_r($bankTotals);
输出:
Array ( [Bank BRI] => 34534534 [Bank BCA] => 1435773657 [Bank CIMB Niaga] => 1338303418 [Bank BNI] => 124124 [Bank Mandiri] => 0 [Bank Permata] => 352352353 )
以上是如何在 PHP 中按列对数组数据进行分组和求和?的详细内容。更多信息请关注PHP中文网其他相关文章!