Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging arrays based on a value of the key

I have two arrays of arrays that have an id key, and I'd like to merge the data together based on that array's key and key value. The data would look something like:

    $color = [
        ['id' => 1, 'color' => 'red'],
        ['id' => 2, 'color' => 'green'],
        ['id' => 3, 'color' => 'blue'],
    ];

    $size = [
        ['id' => 1, 'size' => 'SM'],
        ['id' => 2, 'size' => 'XL'],
        ['id' => 3, 'size' => 'MD'],
        ['id' => 4, 'size' => 'LG'],
    ];

    $combined = [
        ['id' => 1, 'color' => 'red', 'size' => 'SM'],
        ['id' => 2, 'color' => 'green', 'size' => 'XL'],
        ['id' => 3, 'color' => 'blue', 'size' => 'MD'],
        ['id' => 4, 'size' => 'LG'],
    ];

Is there a particularly efficient function or trick for handling something like this? Or should I just loop through the elements of one array and push the contents to the other?

I'm also using Laravel, and the data is a result of an eloquent query, so I can also utilize the collections if it would make the code cleaner.

like image 330
kenshin9 Avatar asked Jul 15 '16 12:07

kenshin9


People also ask

How do I merge two arrays together?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How do you concatenate arrays into arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do I merge two arrays in Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. merge() method is used to merge two or more objects starting with the left-most to the right-most to create a parent mapping object.


1 Answers

Use array_replace_recursive function for easy and fast way

array_replace_recursive($color, $size)
like image 145
Maninderpreet Singh Avatar answered Oct 03 '22 00:10

Maninderpreet Singh