如何用if条件求和数组值

时间:2018-09-08 12:05:10

标签: php arrays if-statement foreach

我从代码中得到了以下数组。

foreach($JobworkMaterialJson as $key => $value) { 
    $decode = json_decode($value->jobcard_jobwork_json); 
}

通过print_r($ decode),我得到以下结果,我想对id相同的值求和。 例如id = 6数量将是25。我们将不胜感激。 谢谢

<pre>Array(
[0] => stdClass Object
    (
        [id] => 9
        [qty] => 5
    )
)
</pre><pre>Array
(
[0] => stdClass Object
    (
        [id] => 6
        [qty] => 10
    )

[1] => stdClass Object
    (
        [id] => 7
        [qty] => 5
    )
) 
</pre><pre>Array
(
[0] => stdClass Object
    (
        [id] => 6
        [qty] => 15
    )
)
</pre>

1 个答案:

答案 0 :(得分:0)

您可以使用关联数组(字典)来跟踪计数。遍历所有输入并更新字典。

示例代码

<?php
$items = array(); // this should be the array you refer to in your question.

$dictionary = array();
foreach($items as $item) {
    if(array_key_exists($item->id, $dictionary)) {
        $dictionary[$item->id] += $item->qty;
    } else {
        $dictionary[$item->id] = $item->qty;
    }
}

$dictionary现在包含总和。例如,$dictionary['6']将返回25