【问题标题】:Sum json quantity with php and mysql [closed]用php和mysql求和json数量[关闭]
【发布时间】: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 questionQuestion Check listthe perfect question 以及如何创建Minimal, Complete and Verifiable ExampleTAKE THE TOUR 我们非常愿意帮助您修复您的代码,但我们不会为您编写代码
  • 我们需要看到的是您创建的 JSON 以及您尝试编写的代码以将其处理为所需的结果。这目前看起来更像是一个规范而不是一个问题。
  • 是的,所以您要求我们中的一个人编写代码以产生指定的输出。那不是一个主题问题。这是一个简单明了的 DIFM
  • 谁支持这样的问题?请阅读当您将鼠标悬停在支持图标上时收到的工具提示并重新评估您的支持
  • 解码json,循环并根据你的条件匹配数据,修改并添加到新数组中,然后编码新数组并保存在数据库中。

标签: php mysql json laravel


【解决方案1】:

你需要对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);

这可能会帮助你实现你想要的。

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2012-06-20
    • 2010-11-12
    相关资源
    最近更新 更多