douan6931 2018-09-08 12:05
浏览 53

如何使用if条件对数组值求和

I got the following array from my code.

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

by the print_r($decode), I got following result now I want to sum values which id is same. e.g. id=6 qty would be 25. help will be highly appreciated. Thanks

<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条回答 默认 最新

  • douguanyan9928 2018-09-08 12:16
    关注

    You can do this using an associative array (a dictionary) to keep track of the counts. Iterate over all the inputs and update the dictionary.

    Example code

    <?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 now contains the sums. For example $dictionary['6'] will return 25.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料