用php和mysql求和json数量

时间:2018-11-01 10:04:17

标签: php mysql json laravel

基本上,我要实现的是遍历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,但我不知道。 谢谢。

1 个答案:

答案 0 :(得分:2)

您需要解码json,然后计算具有相同ID的产品数量,然后将其编码回来。

$data = [];
$pId = [];
$objects = $this->reports()->getBasicMeans($this->id)->get();
foreach($objects as $object)
{
    $newData = json_decode($object);
    $data[$newData->product_id]['name'] = $newData->name;
    $data[$newData->product_id]['product_id'] = $newData->product_id;
    if (!in_array($newData->product_id, $pId)) {
        $pId[] = $newData->product_id;
        $data[$newData->product_id]['quantity'] = $newData->quantity;
    } else {
        $data[$newData->product_id]['quantity'] += $newData->quantity;
    }
}

$json['meanings'] = json_encode($data);

这可以帮助您实现所需的目标。