Search code examples
phparrays

Combine arrays on value


I have two arrays that look like this:

[
    ['id' => '1', 'color'=>'Green'],
    ['id' => '2', 'color'=>'Red'],
    ['id' => '3', 'color'=>'Blue'],
]

and

[
    ['id' => '2', 'size'=>'Small'],
    ['id' => '3', 'size'=>'Medium'],
    ['id' => '4', 'size'=>'Large'],
]

I would like to combine them on the value of the 'id' to produce:

[
    ['id' => '1', 'color'=>'Green', 'size'=>NULL],
    ['id' => '2', 'color'=>'Red', 'size'=>'Small'],
    ['id' => '3', 'color'=>'Blue','size'=>'Medium'],
    ['id' => '4', 'color'=>NULL, 'size'=>'Large'],
]

Note that both arrays may contain the same OR different 'id' values and would like all of the 'id's in the final array.

I have looked at array_merge and array_combine but neither seem to do the job.

Your help is appreciated


Solution

  • You can use array_merge() and isset():

    $arr_a = [
        ['id' => '1', 'color' => 'Green'],
        ['id' => '2', 'color' => 'Red'],
        ['id' => '3', 'color' => 'Blue'],
    ];
    
    $arr_b = [
        ['id' => '2', 'size' => 'Small'],
        ['id' => '3', 'size' => 'Medium'],
        ['id' => '4', 'size' => 'Large'],
    ];
    
    $res = [];
    
    foreach ($arr_a as $item) {
        $id = $item['id'];
        $res[$id] = $item;
        $res[$id]['size'] = NULL;
    }
    
    foreach ($arr_b as $item) {
        $id = $item['id'];
        if (isset($res[$id])) {
            $res[$id] = array_merge($res[$id], $item);
        } else {
            $res[$id] = $item;
            $res[$id]['color'] = NULL;
        }
    }
    
    print_r(array_values($res));
    
    

    Prints

    Array
    (
        [0] => Array
            (
                [id] => 1
                [color] => Green
                [size] => 
            )
    
        [1] => Array
            (
                [id] => 2
                [color] => Red
                [size] => Small
            )
    
        [2] => Array
            (
                [id] => 3
                [color] => Blue
                [size] => Medium
            )
    
        [3] => Array
            (
                [id] => 4
                [size] => Large
                [color] => 
            )
    
    )