按列对数组数据进行分组,并对关联数组的另一列求和
给定一个数据数组,例如:
$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], ];
目标是根据“名称”列对数据进行分组并对数据求和每个组内的“金额”值形成一个平面关联数组。预期输出为:
array ( 'Bank BRI' => 34534534, 'Bank BCA' => 1435773657, 'Bank CIMB Niaga' => 1338303418, 'Bank BNI' => 124124, 'Bank Mandiri' => 0, 'Bank Permata' => 352352353, )
解决方案:
$bankTotals = array(); foreach ($array as $amount) { $bankTotals[$amount['name']] += $amount['amount']; }
此代码初始化一个名为 $bankTotals 的空数组。然后它迭代输入数组,访问代表一行数据的每个子数组。对于每一行,它将“amount”值添加到 $bankTotals 数组中相应的“name”键。此过程有效地按“名称”对行进行分组,并相应地对“金额”值求和。
输出:
array ( 'Bank BRI' => 34534534, 'Bank BCA' => 1435773657, 'Bank CIMB Niaga' => 1338303418, 'Bank BNI' => 124124, 'Bank Mandiri' => 0, 'Bank Permata' => 352352353, )
以上是如何在 PHP 中按列对数组数据进行分组和求和以创建关联数组?的详细内容。更多信息请关注PHP中文网其他相关文章!