-2

I have two arrays by array_merge() that look like this:

 Array(
            [1] => Array(
                  [date] => 2018-09-25
                  [size_one] => 'XL'
                  [name_one] => 'Shoes'
                )
            [2] => Array(
                    [date] => 2018-09-25
                    [size_two] => 'L'
                    [name_two] => 'Shirt'
                )
            [3] => Array(
                    [date] => 2018-09-26
                    [size_two] => 'L'
                    [name_two] => 'Shirt'
                )
            )

If same date value, I need as a result something like the following:

Array(
                [1] => Array(
                      [date] => 2018-09-25
                      [size_one] => 'XL'
                      [name_one] => 'Shoes'
                      [size_two] => 'L'
                      [name_two] => 'Shirt'
                    )
                [2] => Array(
                        [date] => 2018-09-26
                        [size_two] => 'L'
                        [name_two] => 'Shirt'
                    )
                )

want to be able to put these into an array for laravel, Can someone show me the proper way to merge these arrays?

  • You can use laravel collection. First you need to group by date, then merge each group and remove the keys. `$result = collect($input) ->groupBy('date') ->map(function ($item) { return array_merge(...$item->toArray()); }) ->values();` – Илья Зеленько Sep 24 '18 at 18:25

1 Answers1

0

Using array_merge and array_key_exists functions, with some basic foreach looping and conditionals, you can try the following (steps explained in the code comments):

// $input is your input array

// initialize output array
$output = array();

// loop over the input
foreach ($input as $key => $value) {

    // check if the date key is already set in the output or not
    if ( array_key_exists($value['date'], $output) ) {

        // this is duplicate based on date - merge into output
        $output[$value['date']] = array_merge($output[$value['date']], 
                                              $value);
    } else {

        // new entry for date
        $output[$value['date']] = $value;
    }
}
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57