Search code examples
phparraysmultidimensional-arraymerge

Merge two 2d arrays by shared column value


I know this is quite easily accomplished with a foreach, then a while->list, etc procedure, (I have already accomplished it), however I sense that my code is a bit dirty and it doesn't look like the best solution... I'm looking to use native PHP array functions to do the following:

I have two arrays that look like this:

[
    ['rank' => '579', 'id' => '1'],
    ['rank' => '251', 'id' => '2'],
]

and

[
    ['size' => 'S', 'status' => 'A', 'id' => '1'],
    ['size' => 'L', 'status' => 'A', 'id' => '2'],
]

And I need merge them to produce:

[
    ['size' => 'S', 'status' => 'A', 'id' => '1', 'rank' => '579'],
    ['size' => 'L', 'status' => 'A', 'id' => '2', 'rank' => '251'],
]

Is there a way to be able to merge two arrays with the id value (or any other) without going into a endless set of foreachs?


Solution

  • Use array_merge_recursive()

    $array = array_merge_recursive($array1, $array2);
    

    or make your own function (it may be faster)

    function my_array_merge(&$array1, &$array2) {
        $result = Array();
        foreach($array1 as $key => &$value) {
            $result[$key] = array_merge($value, $array2[$key]);
        }
        return $result;
    }
    $array = my_array_merge($array1, array2);
    print_r($array);