douxue4242 2017-04-20 18:28
浏览 18
已采纳

获取具有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.

  • 写回答

1条回答 默认 最新

  • dptdb84606 2017-04-20 18:58
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?