【问题标题】:How to check same value in a JSON object array and combine them together?如何检查 JSON 对象数组中的相同值并将它们组合在一起?
【发布时间】:2021-01-17 04:08:14
【问题描述】:

我有这个 JSON 对象数组。我需要检查相同的日期并合并金额。我需要在 PHP 中执行此操作。 (我正在使用 Laravel)

[
{date : 2020-09-28, amount : 69.95}
{date : 2020-09-28, amount : 69.95}
{date : 2020-10-01, amount : 69.95}
{date : 2020-10-01, amount : 69.95}
{date : 2020-10-01, amount : 319.95}
]

所以输出应该是这样的:

[
   {date : 2020-09-28, amount : 139.9}
   {date : 2020-10-01, amount : 459.85}
]

请问最好的实现方式是什么?

这是我尝试过的解决方案:

$new_values = array();
        foreach ($orders as $order) {
            $order_total = $order->order_checkout->shoppingcart->getTotalPrice();
            $order_date = $order->created_at->format('Y-m-d');
            print_r($order_date);
            print(" - ");
            print_r($order_total);
            print "<br/>";

            if (array_key_exists($order_date, $new_values)) {
                echo $order_date . " found";
            } else {
                echo "Not found";
            }

            array_push($new_values, array($order_date => $order_total));
        }
        print("<br>");
        print_r($new_values);

但它没有找出重复项。

【问题讨论】:

  • 请阅读How to Ask。我们不是在这里简单地为您提供代码,应该努力并先尝试一些东西。
  • 提供@04FS所说的代码,你应该努力
  • @04FS 请检查。我已经添加了我正在研究的解决方案。 PHP 新手。
  • @Jerson 请检查。添加了我的代码。
  • “但它没有找出重复项。” - 当然没有。您正在尝试在日期值下查找存储在数组中的元素作为键 - 但您从未将其用作键,您只是将您的项目推送到具有正常数字索引的数组中。

标签: php arrays json laravel


【解决方案1】:

这很好用

     $json = '[{
        "date": "2020 - 09 - 28",
        "amount": 69.95
      },
      {
        "date": "2020 - 09 - 28",
        "amount": 69.95
      },
      {
        "date": "2020 - 10 - 01",
        "amount": 69.95
      },
      {
        "date": "2020 - 10 - 01",
        "amount": 69.95
      },
      {
        "date": "2020 - 10 - 01",
        "amount": 319.95
      }
    ]';

    $decode = json_decode($json,true);

    $res  = array();

    foreach($decode as $key => $vals){
        if(($index = array_search($vals['date'], array_column( $res, 'date'))) !== false) {
            $res[$index]['amount'] += $vals['amount'];
            $res[$index]['date'] = $vals['date'];
        } else {
            $res[] = $vals;
        }
    }

    echo json_encode($res,JSON_PRETTY_PRINT);

输出:

    [
        {
            "date": "2020 - 09 - 28",
            "amount": 139.9
        },
        {
            "date": "2020 - 10 - 01",
            "amount": 459.85
        }
    ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多