對數組資料進行分組並對扁平關聯數組的值進行求和
給定一組關聯數據,挑戰涉及按一列將元素進行分組(例如,「名稱」)並對另一列的值進行求和(例如, '數量')。結果是一個扁平關聯數組,其中組作為鍵,求和金額作為值。
提供的陣列資料
$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中文網其他相關文章!