Aleksa
Aleksa

Reputation: 99

Get rows with stdClass objects column and sum elements with same id

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.

Upvotes: 0

Views: 165

Answers (1)

mdmg
mdmg

Reputation: 163

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

Upvotes: 1

Related Questions