問題:
給定一個包含鍵值對的數組,根據特定列的值將資料分組,並對另一列的資料求和。例如,如果您有以下數組:
$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中文網其他相關文章!