-1

How can I sum this array by value? Just sum value of [jumlah] group by [Kondisi].

Array 
( 
[0] => stdClass Object 
    ( 
        [Kondisi] => one
        [jumlah] => 2
    ) 
[1] => stdClass Object 
    ( 
        [Kondisi] => two 
        [jumlah] => 3
    ) 
[2] => stdClass Object 
    ( 
        [Kondisi] => three
        [jumlah] => 4
    ) 
[3] => stdClass Object 
    ( 
        [Kondisi] => one
        [jumlah] => 3
    ) 
[4] => stdClass Object 
    ( 
        [Kondisi] => two
        [jumlah] => 1
    ) 
[5] => stdClass Object 
    ( 
        [Kondisi] => three
        [jumlah] => 3
    ) 
)

I have try How to sum all column values in multi-dimensional array?, but didn't help.

I want output like this:

Array 
( 
[0] => stdClass Object 
    ( 
        [Kondisi] => one 
        [jumlah] => 5
    ) 
[1] => stdClass Object 
    ( 
        [Kondisi] => two
        [jumlah] => 4
    ) 
[2] => stdClass Object 
    ( 
        [Kondisi] => three
        [jumlah] => 7
    ) 
) 
Mading Ne
  • 133
  • 2
  • 13

1 Answers1

3

A sample code can be:

$sums = [];

// `$objects` is your initial array 
foreach ($objects as $object) {
    // here we check if key `$object->Kondisi` exists in `$sums` array
    if (empty($sums[$object->Kondisi])) {
        // if `no` - this is new object, store it as is
        $sums[$object->Kondisi] = $object;
    } else {
        // if `yes` - add `jumlah` value to existing `jumlah` property
        $sums[$object->Kondisi]->jumlah += $object->jumlah;
    }
}

// use `array_values` to get 0-indexed array
print_r(array_values($sums));
u_mulder
  • 54,101
  • 5
  • 48
  • 64