【问题标题】:how to sum array values with if condition如何将数组值与if条件相加
【发布时间】:2018-09-08 12:05:10
【问题描述】:

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

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>

【问题讨论】:

  • 你如何创建这个数组分享那个代码?
  • 如果你从数据库查询中得到这个数组,如果你显示查询,那么有人会告诉你如何在查询中完成所有这些操作
  • foreach($JobworkMaterialJson as $key => $value) { $decode = json_decode($value->jobcard_jobwork_json); }
  • 您可以编辑您的问题以添加额外信息。如果您要添加它的代码,最好编辑问题,因为代码在评论中不可读

标签: php arrays if-statement foreach


【解决方案1】:

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

示例代码

<?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

【讨论】:

  • 它只包含 $dictionary['6'] => 10
猜你喜欢
  • 2019-03-24
  • 2016-06-06
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 2023-03-25
  • 2021-09-30
相关资源
最近更新 更多