Home > Software engineering >  Combine and Sum the data with the same date
Combine and Sum the data with the same date

Time:10-25

Forgive me for my bad english because it's not my first language I have a blockers on how to combine and add some of the data I have this data from my first collection

first Collection

[
   {
      "dateTime": "10/01/2022",
      "gc": 0,
      "credit": 20,
      "debit": 1000,
      "voucher": 0,
      "e_gift": 0,
      "cash": 3000
    }, 
    {
      "dateTime": "10/02/2022",
        "gc": 0,
        "credit": 10,
        "debit": 10,
        "voucher": 0,
        "e_gift": 0,
        "cash": 100
    },
]

2nd Collection

 [
    {
         "dateTime": "10/01/2022",
         "Gross Total": 6000,
         "Discount": 300
      },
      {
           "dateTime": "10/02/2022",
           "Gross Total": 4000,
           "Discount": 100
       },
    ]

What result i want is they will combine based on date and all the data from first collection will be add to gross total result is like this

[
    {
      "dateTime": "10/01/2022",
        "gc": 0,
        "credit": 20,
        "debit": 1000,
        "voucher": 0,
        "e_gift": 0,
        "cash": 3000
        "Gross Total": 6000,
        "Discount": 300
        "total amount" : 10020  

    },
{
       "dateTime": "10/02/2022",
        "gc": 0,
        "credit": 10,
        "debit": 10,
        "voucher": 0,
        "e_gift": 0,
        "cash": 100
        "Gross Total": 4000,
        "Discount": 100,
        "total amount" : 4120

    }, 
]   

CodePudding user response:

let's call them collection1 and collection2, using Collection methods such as merge and push this should work:

$merged = collect();
            foreach(collection1 as $e){
                $temp = collect($e)->merge($collect2->where('dateTime', $e['dateTime'])->first());
                $merged->push($temp);
            }
            return $merged;

Notice that i've created these variables using a sample from your code above:

 $collect2 = collect([
            [
                 "dateTime"=> "10/01/2022",
                 "Gross Total"=> 6000,
                 "Discount"=> 300
                ],
             [
                   "dateTime"=> "10/02/2022",
                   "Gross Total"=> 4000,
                   "Discount"=> 100
                ],
        ]);

please check the Documentation for more details

  • Related