【发布时间】:2019-04-05 13:02:29
【问题描述】:
基本上我想要实现的是循环遍历 json 对象,查找是否有具有相同 product_id 的对象,如果有的话,应该对这些对象的数量求和。 代码:
$data = [];
$objects = $this->reports()->getBasicMeans($this->id)->get();
foreach($objects as $object)
{
$data[] = $object->json;
}
$json['meanings'] = $data;
这就是我编写查询的方式:
public function scopegetBasicMeans($query, $market = null)
{
$query->where('market_id', $market)->where('type', 1)
->join('product_assets', 'product_assets.report_id', '=', 'reports.id')->select(
DB::raw('
CONCAT("[", group_concat(substring(product_assets.resources, 2, length(product_assets.resources) - 2)), "]") AS json
')
);
}
结果:
"meanings": [
"[
{\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 4},
{\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 1},
{\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 1},
{\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 4},
{\"name\": \"Product 2\", \"product_id\": \"2\", \"quantity\": 4},
{\"name\": \"Product 3\", \"product_id\": \"3\", \"quantity\": 4},
{\"na]"
]
所以基本上它应该搜索具有相同 product_id 的对象,如果有多个具有相同 product_id 的对象,它应该将数量相加 具有相同 product_id 的所有对象合二为一,因此结果应如下所示:
预期结果:
"meanings": [
"[
{\"name\": \"Product 1\", \"product_id\": \"1\", \"quantity\": 10},
{\"name\": \"Product 2\", \"product_id\": \"2\", \"quantity\": 4},
{\"name\": \"Product 3\", \"product_id\": \"3\", \"quantity\": 4},
{\"na]"
]
这是否可能,我怎么能做到这一点,我刚开始使用 mysql json,我不知道。 谢谢。
【问题讨论】:
-
欢迎,为了提高您在 SO 上的体验,请阅读如何询问On Topic question、Question Check list 和 the perfect question 以及如何创建Minimal, Complete and Verifiable Example 和 TAKE THE TOUR 我们非常愿意帮助您修复您的代码,但我们不会为您编写代码
-
我们需要看到的是您创建的 JSON 以及您尝试编写的代码以将其处理为所需的结果。这目前看起来更像是一个规范而不是一个问题。
-
是的,所以您要求我们中的一个人编写代码以产生指定的输出。那不是一个主题问题。这是一个简单明了的 DIFM
-
谁支持这样的问题?请阅读当您将鼠标悬停在支持图标上时收到的工具提示并重新评估您的支持
-
解码json,循环并根据你的条件匹配数据,修改并添加到新数组中,然后编码新数组并保存在数据库中。