简体   繁体   中英

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

I have this JSON object array. I need to check for same dates and combine the amount. I need to do this in PHP. (I'm using 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}
]

So the output should be like this:

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

What is the best way to implement this please?

This is the solution I have tried:

$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);

But it doesn't find out the duplicates.

This works fine

     $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);

Output with :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM