如何按值求和该数组? [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
)
)
我尝试了How to sum all column values in multi-dimensional array?,但没有帮助。
我想要这样的输出:
Array
(
[0] => stdClass Object
(
[Kondisi] => one
[jumlah] => 5
)
[1] => stdClass Object
(
[Kondisi] => two
[jumlah] => 4
)
[2] => stdClass Object
(
[Kondisi] => three
[jumlah] => 7
)
)
答案 0 :(得分:3)
示例代码可以是:
$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));