Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

php - Group array data on one column and sum data from another column

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,
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, first you need $amountsArray to get assigned the values you listed, somehow. Then:

$bankTotals = array();
foreach($amountsArray as $amount)
{
  $bankTotals[$amount['name']] += $amount['amount'];
}

After this, $bankTotals is an array indexed on name of the bank, with the value of the total amount for the bank. You can use this array as you see fit from here.

One thing that might be useful is another foreach loop to print it all out:

foreach($bankTotals as $name => $amount)
{
  echo $name.".....".$amount."
";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...