获取具有 stdClass 对象列的行并求和具有相同 id 的元素
Posted
技术标签:
【中文标题】获取具有 stdClass 对象列的行并求和具有相同 id 的元素【英文标题】:Get rows with stdClass objects column and sum elements with same id 【发布时间】:2017-09-17 12:58:53 【问题描述】:我有一个订单表,其中一列名为“ordered_goods”如下所示:
"["product_id":"3","qua":"3","we":"1350","product_id":"4","qua":"3","we":"1215","product_id":"5","qua":"5","we":"810"]"
当我收到所有“status = 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));
Array map 将数组作为第二个参数(在本例中为每一行的ordered_goods),第一个参数是一个匿名函数,它将数组的每个元素作为参数。当找到 id = 3 的产品时,返回 qua 属性并将其与 array_sum 相加为 $amount
【讨论】:
感谢您的回复和解释。这两天我一直在苦苦挣扎。非常感谢!以上是关于获取具有 stdClass 对象列的行并求和具有相同 id 的元素的主要内容,如果未能解决你的问题,请参考以下文章