本文介绍了如何按值求和数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何按值求和该数组? [Kondisi]的[jumlah]组的总和.
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.
我想要这样的输出:
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));
这篇关于如何按值求和数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!