Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何按值对数组求和?_Php_Arrays - Fatal编程技术网

Php 如何按值对数组求和?

Php 如何按值对数组求和?,php,arrays,Php,Arrays,如何按值对该数组求和?[Kondisi]对[jumlah]群的求和值 Array ( [0] => stdClass Object ( [Kondisi] => one [jumlah] => 2 ) [1] => stdClass Object ( [Kondisi] => two [jumlah] => 3 ) [2] => stdCla

如何按值对该数组求和?[Kondisi]对[jumlah]群的求和值

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
    ) 
)
我试过了,但没有帮助

我想要这样的输出:

Array 
( 
[0] => stdClass Object 
    ( 
        [Kondisi] => one 
        [jumlah] => 5
    ) 
[1] => stdClass Object 
    ( 
        [Kondisi] => two
        [jumlah] => 4
    ) 
[2] => stdClass Object 
    ( 
        [Kondisi] => three
        [jumlah] => 7
    ) 
) 
示例代码可以是:

$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));