7

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,
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Chandra
  • 53
  • 1
  • 1
  • 6

5 Answers5

9

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'];
}

Output: (Demo)

Warning: Undefined array key "Bank BRI"

Warning: Undefined array key "Bank BCA"

Warning: Undefined array key "Bank CIMB Niaga"

Warning: Undefined array key "Bank BNI"

Warning: Undefined array key "Bank Mandiri"

Warning: Undefined array key "Bank Permata"
array (
  'Bank BRI' => 34534534,
  'Bank BCA' => 1435773657,
  'Bank CIMB Niaga' => 1338303418,
  'Bank BNI' => 124124,
  'Bank Mandiri' => 0,
  'Bank Permata' => 352352353,
)

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."\n";
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Jeffrey Blake
  • 9,659
  • 6
  • 43
  • 65
  • @Jeffrey Blake, what if we have two keys to merge. Let's say Bank Name and Bank Address, it only will sum the amount if only the have same Name and Address ... Actually have those problem right now ... Please help – Mauliardiwinoto Nov 21 '19 at 05:29
5
<?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;
}
Husni
  • 1
  • 2
  • Performing nested iterations (via `bank_exists()`) is not ideal programming -- it is needlessly inefficient. Use the result array as a lookup as you iterate. Other answers on this page are more efficient. – mickmackusa May 19 '22 at 00:54
4

I would rather add

$bankTotals = array();
foreach($amountsArray as $amount)
{
 if(isset($bankTotals[$amount['name']]))
    $bankTotals[$amount['name']] += $amount['amount'];
 else
    $bankTotals[$amount['name']] = $amount['amount'];
}
Shubham
  • 37
  • 4
0

@Shubham's loop is a perfectly adequate technique.

You may wish to employ array_reduce() if you want to:

  • avoid generating a global-scoped variable or
  • want to work with a returned value or
  • generally prefer a functional style

The null coalescing operator prevents generating any warnings/errors from adding to not-yet-declared elements in the result array

Code: (Demo)

var_export(
    array_reduce(
        $array,
        function($carry, $row) {
            $carry[$row['name']] = ($carry[$row['name']] ?? 0) + $row['amount'];
            return $carry;
        }
    )
);

Or from PHP7.4 with arrow function syntax: (Demo)

var_export(
    array_reduce(
        $array,
        fn($carry, $row) => array_merge($carry, [$row['name'] => ($carry[$row['name']] ?? 0) + $row['amount']]),
        // or fn($carry, $row) => $carry + [$row['name'] => ($carry[$row['name']] ?? 0) + $row['amount']],
        []
    )
);

Output:

array (
  'Bank BRI' => 34534534,
  'Bank BCA' => 1435773657,
  'Bank CIMB Niaga' => 1338303418,
  'Bank BNI' => 124124,
  'Bank Mandiri' => 0,
  'Bank Permata' => 352352353,
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1
$a = arrayofindonesianbanks;

foreach ($a as $anarrays) {
        echo "$anarrays[name]."  ".$anarrays[amount]";
    }
}

see foreach in php.