Merging two multidimensional arrays on specific key

前端 未结 7 1897
南方客
南方客 2020-11-28 13:13

Let\'s say I have following arrays:

Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
            


        
相关标签:
7条回答
  • 2020-11-28 13:48

    This can be easily done using the 3-parameter form of array_column to re-index your second array by the id value and then looping over the first array, merging the contents of the matching second value (where it exists):

    $second = array_column($second, null, 'id');
    foreach ($first as &$subject) {
        $subject = array_merge($subject, $second[$subject['id']] ?? []);
    }
    

    Output:

    Array
    (
        [0] => Array
            (
                [id] => 5
                [name] => Education
                [title] => Edu
            )
        [1] => Array
            (
                [id] => 4
                [name] => Computers
                [title] => Comp
            )
        [3] => Array
            (
                [id] => 7
                [name] => Science
                [title] => Sci
            )
        [4] => Array
            (
                [id] => 1
                [name] => Sports
                [title] => Sport
            )
    )
    

    Demo on 3v4l.org

    This has the advantage over Will B.'s answer of not re-indexing the first array. It's also slightly faster (my tests show ~10%) due to only having one call to array_column and none to array_values.

    Update

    This code can actually be sped up even more by using the array union operator (+) (thanks @mickmackusa):

    $second = array_column($second, null, 'id');
    foreach ($first as &$subject) {
        $subject += $second[$subject['id']] ?? [];
    }
    

    The output of this code is the same as above, but it runs about 10% faster again.

    Demo on 3v4l.org

    0 讨论(0)
提交回复
热议问题