对数组数据进行分组并对扁平关联数组的值进行求和
给定一组关联数据,挑战涉及按一列对元素进行分组(例如,“名称”)并对另一列的值进行求和(例如, '数量')。结果是一个扁平关联数组,其中组作为键,求和金额作为值。
提供的数组数据
$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], ];
解决方案
要按“名称”对数组数据进行分组并对“金额”值求和,请按照以下步骤操作:
代码:
$bankTotals = array(); foreach($array as $amount) { $bankTotals[$amount['name']] += $amount['amount']; }
输出:
array ( 'Bank BRI' => 34534534, 'Bank BCA' => 1435773657, 'Bank CIMB Niaga' => 1338303418, 'Bank BNI' => 124124, 'Bank Mandiri' => 0, 'Bank Permata' => 352352353, )
$bankTotals 数组现在包含分组和求和的数据,以银行名称作为键,总金额作为值。这个扁平关联数组已准备好在您的应用程序中进一步使用。
以上是如何对数组数据进行分组和求和以创建扁平关联数组?的详细内容。更多信息请关注PHP中文网其他相关文章!