我有我的数组数据,如下所示:
Array ( [0] => Array ( [name] => Bank BRI [amount] => 0 ) [1] => Array ( [name] => Bank BRI [amount] => 0 ) [2] => Array ( [name] => Bank BCA [amount] => 1412341234 ) [3] => Array ( [name] => Bank CIMB Niaga [amount] => 532532552 ) [4] => Array ( [name] => Bank BRI [amount] => 34534534 ) [5] => Array ( [name] => Bank CIMB Niaga [amount] => 453425243 ) [6] => Array ( [name] => Bank BRI [amount] => 0 ) [7] => Array ( [name] => Bank BNI [amount] => 124124 ) [8] => Array ( [name] => Bank CIMB Niaga [amount] => 352345623 ) [9] => Array ( [name] => Bank BCA [amount] => 23432423 ) [10] => Array ( [name] => Bank Mandiri [amount] => 0 ) [11] => Array ( [name] => Bank BCA [amount] => 0 ) [12] => Array ( [name] => Bank BCA [amount] => 0 ) [13] => Array ( [name] => Bank Permata [amount] => 352352353 ) )
如何根据相同的“银行名称”对“金额”进行汇总.
我的数据应该如下所示:
Bank BRI........... with '*total amount*' Bank BCA........... with '*total amount*' Bank CIMB NIAGA.... with '*total amount*' Bank BNI........... with '*total amount*' Bank Mandiri....... with '*total amount*' Bank Permata....... with '*total amount*'
<?PHP // array of bank structure $banks = array(); $banks[] = array('name'=>'Bank BRI','amount'=>rand()); $banks[] = array('name'=>'Bank BRI','amount'=>rand()); $banks[] = array('name'=>'Bank BCA','amount'=>rand()); $banks[] = array('name'=>'Bank CIMB','amount'=>rand()); $banks[] = array('name'=>'Bank BNI','amount'=>rand()); $banks[] = array('name'=>'Bank Mandiri','amount'=>rand()); $banks[] = array('name'=>'Bank Permata','amount'=>rand()); // begin the iteration for grouping bank name and calculate the amount $amount = array(); foreach($banks as $bank) { $index = bank_exists($bank['name'],$amount); if ($index < 0) { $amount[] = $bank; } else { $amount[$index]['amount'] += $bank['amount']; } } print_r($amount); //display // for search if a bank has been added into $amount,returns the key (index) function bank_exists($bankname,$array) { $result = -1; for($i=0; $i<sizeof($array); $i++) { if ($array[$i]['name'] == $bankname) { $result = $i; break; } } return $result; }