按列將數組資料分組,並將關聯數組的另一列求和
給定一個資料數組,例如:
$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中文網其他相關文章!