2017-04-20 31 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

相關問題