2017-04-20 49 views
0

我有订单表,其中一个名为列“ordered_goods”是这样的:获取行与stdClass的对象具有相同的id列,和元素

"[{"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

我试图做的方法很多,但瓦特没有成功。显然我不知道该怎么做。

在此先感谢您的帮助。

回答

1

如果列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以$金额结算

+1

感谢您的回复和解释。两天我挣扎着。非常感谢! – Alex

相关问题