在一列上对数组数据进行分组,并对另一列中的数据求和
我的数组数据如下所示:
I have my array data as shown below:
$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],
];
如何根据相同的银行名称"计算金额".
How to sum 'amount' based on same 'bank name'.
我的结果应该显示分组名称及其总和:
My result should show grouped names and their summed amount:
array (
'Bank BRI' => 34534534,
'Bank BCA' => 1435773657,
'Bank CIMB Niaga' => 1338303418,
'Bank BNI' => 124124,
'Bank Mandiri' => 0,
'Bank Permata' => 352352353,
)
推荐答案
<?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 BRI','amount'=>rand());
$banks[] = array('name'=>'Bank CIMB','amount'=>rand());
$banks[] = array('name'=>'Bank BRI','amount'=>rand());
$banks[] = array('name'=>'Bank BNI','amount'=>rand());
$banks[] = array('name'=>'Bank CIMB','amount'=>rand());
$banks[] = array('name'=>'Bank BCA','amount'=>rand());
$banks[] = array('name'=>'Bank Mandiri','amount'=>rand());
$banks[] = array('name'=>'Bank BCA','amount'=>rand());
$banks[] = array('name'=>'Bank BCA','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;
}
相关文章