samedi 14 août 2021

Array Merge with condition

Array 1:

  [ 
      {
        "product_name": "Redme note 7"
        "quantity": "548.00"
        "purchase_price": "10000.00"
        "product_id": 1
      }
      {
        "product_name": "Redme note 7"
        "quantity": "150.00"
        "purchase_price": "19000.00"
        "product_id": 1
      }
      {
        "product_name": "Fresh Water 5 Litre"
        "quantity": "20.00"
        "purchase_price": "70.00"
        "product_id": 2
      }
      {
        "product_name": "Fresh Water 5 Litre"
        "quantity": "348.00"
        "purchase_price": "80.00"
        "product_id": 2
      }
      {
        "product_name": "Fresh Water 5 Litre"
        "quantity": "1067.00"
        "purchase_price": "800.00"
        "product_id": 2
      }
    ]

Array 2:

[
  {
    "sales_quantity": "14.00"
    "product_id": 1
    "purchase_price": "10000.00"
  }
  {
    "sales_quantity": "7.00"
    "product_id": 2
    "purchase_price": "70.00"
  }
  {
    "sales_quantity": "10.00"
    "product_id": 2
    "purchase_price": "80.00"
  }
]

Expected Output:

 [ 
          {
            "product_name": "Redme note 7"
            "quantity": "548.00"
            "purchase_price": "10000.00"
            "product_id": 1
            "sales_quantity":14
          }
          {
            "product_name": "Redme note 7"
            "quantity": "150.00"
            "purchase_price": "19000.00"
            "product_id": 1
             "sales_quantity":0
          }
          {
            "product_name": "Fresh Water 5 Litre"
            "quantity": "20.00"
            "purchase_price": "70.00"
            "product_id": 2
            "sales_quantity":14
          }
          {
            "product_name": "Fresh Water 5 Litre"
            "quantity": "348.00"
            "purchase_price": "80.00"
            "product_id": 2
               "sales_quantity":10
          }
          {
            "product_name": "Fresh Water 5 Litre"
            "quantity": "1067.00"
            "purchase_price": "800.00"
            "product_id": 2
              "sales_quantity":0
          }
        ]

I have tried with following code but it doesn't give me expected output

collect(array_merge($products, $sales_products))
              ->groupBy('product_id','purchase_price')
              ->values()
              ->map(fn ($person) => $person->reduce(fn ($acc, $cur) => $acc->merge($cur), collect()))
              ->each(static function ($person) {
                  if (!$person->has('sales_quantity')) {
                      $person->put('sales_quantity', '0');
                  }
              })
        ->toArray();


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire