获取具有stdClass对象列的行和具有相同id的sum元素
I have table with orders, where one column named "ordered_goods" look like this:
"[{"product_id":"3","qua":"3","we":"1350"},{"product_id":"4","qua":"3","we":"1215"},{"product_id":"5","qua":"5","we":"810"}]"
When I get all orders with "status = 0" it look like this:
$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"}]
What I'm trying is to sum all "qua" where "product_id" = 3.
I tried to do it in many ways, but without success. Obviously I do not know how to do it.
Thanks in advance for your help.
我有订单表,其中一个名为“ordered_goods”的列如下所示: p> \ ñ
“[{” PRODUCT_ID “:” 3" , “QUA”: “3”, “我们”: “1350”},{ “PRODUCT_ID”: “4”, “QUA”:“3 “ ”我们“: ”1215“},{ ”PRODUCT_ID“: ”5“, ”QUA“: ”5“, ”我们“: ”810“}]”代码> p>
当我获得“status = 0”的所有订单时,它看起来像这样: p>
$ orders_status_zero = $ this-> db-> get_where('orders' ,array('status'=>'0')) - > result_array();
foreach($ orders_status_zero as $ row):
print_r($ row ['ordered_goods']); //结果:
[{“product_id”:“3”,“qua”:“3”,“我们”:“1350”},{“product_id”:“4”,“qua”:“3 “ ”我们“: ”1215“},{ ”PRODUCT_ID“: ”5“, ”QUA“: ”5“, ”我们“: ”810“}]
上[{ ”PRODUCT_ID“: ”3“,” QUA “:” 4" , “我们”: “1350”},{ “PRODUCT_ID”: “4”, “QUA”: “4”, “我们”: “1620”},{ “PRODUCT_ID”: “5” “QUA”: “4”, “我们”: “648”},{ “PRODUCT_ID”: “6”, “QUA”: “5”, “我们”: “864”},{ “PRODUCT_ID”:” 8" , “QUA”: “4”, “我们”: “864”}]
上[{ “PRODUCT_ID”: “3”, “QUA”: “4”, “我们”: “1800”},{ “PRODUCT_ID”: “4”, “QUA”: “3”, “我们”: “1215”},{ “PRODUCT_ID”: “6”, “QUA”: “4”, “我们”: “864”} ]
code> pre>
我正在尝试的是将“product_id”= 3的所有“qua”相加。 p>
我尝试过 在很多方面做到这一点,但没有成功。 显然我不知道怎么做。 p>
先谢谢你的帮助。 p>
div>
If your column ordered_goods is storing json, you could do it like this
$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));
}
Array map takes an array as second parameter (ordered_goods of each row in this case) and the first parameter is an anonymous function that takes each element of the array as parameter. When an product with id = 3 is found, the qua property is returned and array_sum sum it in $amount