How to sum array by value?

前端 未结 1 1531
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 10:47

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

Array 
( 
[0] => stdClass Object 
    ( 
        [Kondisi] => one
               


        
相关标签:
1条回答
  • 2021-01-29 11:14

    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));
    
    0 讨论(0)
提交回复
热议问题