我有带有订单的表,其中一个名为“ ordered_goods”的列如下所示:

"[{"product_id":"3","qua":"3","we":"1350"},{"product_id":"4","qua":"3","we":"1215"},{"product_id":"5","qua":"5","we":"810"}]"

当我获得“状态= 0”的所有订单时,它看起来像这样:

$orders_status_zero   =   $this->db->get_where('orders', array('status' => '0'))->result_array();
foreach ($orders_status_zero as $row):
print_r($row['ordered_goods']); // RESULT:

[{"product_id":"3","qua":"3","we":"1350"},{"product_id":"4","qua":"3","we":"1215"},{"product_id":"5","qua":"5","we":"810"}]
[{"product_id":"3","qua":"4","we":"1350"},{"product_id":"4","qua":"4","we":"1620"},{"product_id":"5","qua":"4","we":"648"},{"product_id":"6","qua":"5","we":"864"},{"product_id":"8","qua":"4","we":"864"}]
[{"product_id":"3","qua":"4","we":"1800"},{"product_id":"4","qua":"3","we":"1215"},{"product_id":"6","qua":"4","we":"864"}]


我正在尝试对所有“ qua”求和,其中“ product_id” = 3。

我尝试了许多方法,但是没有成功。显然我不知道该怎么做。

在此先感谢您的帮助。

最佳答案

如果您的ordered_goods列存储的是json,则可以这样做

$amount = 0;
foreach ($orders_status_zero as $row){
    $array = (array)json_decode($row['ordered_goods']);
    $amount +=  array_sum(array_map(function($element){
        if($element->product_id == 3)
            return $element->qua;
    }, $array));
}


数组映射将数组作为第二个参数(在这种情况下为每行的ordered_goods),而第一个参数是一个匿名函数,将数组的每个元素作为参数。当找到id = 3的产品时,将返回qua属性,并且array_sum将其加到$ amount中

08-27 12:53