Merge second array into first array where row value in first array matches row key in second array

Viewed 853

I would like to merge the associative elements from my second array into my first array where the second array's subarray key matches a row's epg_channel_id value.

First array:

[
    [
        'num' => 1,
        'name' => 'name 1',
        'epg_channel_id' => 'ch111',
        'added' => '1505435915',
    ],
    [
        'num' => 2,
        'name' => 'name 2',
        'epg_channel_id' => 'ch222',
        'added' => '1505435915',
    ],
    [
        'num' => 3,
        'name' => 'name 3',
        'epg_channel_id' => 'ch333',
        'added' => '1505435915',
    ],
    [
        'num' => 4,
        'name' => 'name 4',
        'epg_channel_id' => 'ch444',
        'added' => '1505435915'
    ]
]

And the second array:

[
    ['ch000' => 'Um9jayBJbiBSaW8='],
    ['ch111' => 'Um9jayBJbiBSaW8='],
    ['ch222' => 'Um9jayBJbiBSaW8='],
    ['ch333' => 'Um9jayBJbiBSaW8='],
    ['ch444' => 'Um9jayBJbiBSaW8=']
]

Desired output (for one row):

Array
(
  [0] => Array
  (
    [num] => 1
    [name] => name 1
    [epg_channel_id] => ch111
    [added] => 1505435915
    [ch111] => Um9jayBJbiBSaW8= 
  )
  ...
)

I tried array_recursive, array merge and not works.

8 Answers

The bad news is that your second array is not suitably structured to serve as a lookup array. The good news is that the step to flatten the structure into a simple associative array is quite easy.

Once the lookup is declared, just use a loop and modify-by-reference as you use array union syntax to append the desired key-value pairs.

I do not recommend any answers that are using nested loops -- they will not perform efficiently.

Code: (Demo)

$lookup = array_merge(...$array2);
foreach ($array as &$row) {
    $row += [$row['epg_channel_id'] => $lookup[$row['epg_channel_id']]];
}
var_export($array);
Related