簡體   English   中英

如何檢查 JSON 對象數組中的相同值並將它們組合在一起?

[英]How to check same value in a JSON object array and combine them together?

我有這個 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);

但它沒有找出重復項。

這工作正常

     $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
        }
    ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM