What is the simpliest way to do merge multiple array values into a single multi-dimension array. For example, I have several arrays ($arr_a, $arr_b) like,
Array (  => a1  => a2  => a3 ) Array (  => b1  => b2  => b3 )
The keys array ($keys) for new array like
Array (  => key1  => key2  => key3 )
I want combine these array to a single array with keys like
Array (  => Array ( [key1] => a1 [key2] => a2 [key3] => a3 )  => Array ( [key1] => b1 [key2] => b2 [key3] => b3 ) )
I tried this this code
$ouput = array_map(null, $arr_a, $arr_b);
But I can’t add array keys by this code..
To combine each array with the keys, you can use something like
array_combine() which can take your keys array and add them to the value array.
To apply this and combine the array, using
array_combine as the callback makes it possible with combining the two arrays as well. Using arrow functions also means you don’t have to worry about the scope of the keys array..
$arr_a = ['a1', 'a2', 'a3']; $arr_b = ['b1', 'b2', 'b3']; $keys = ['key1', 'key2', 'key3']; print_r(array_map(fn ($arr) => array_combine($keys, $arr), [$arr_a, $arr_b]));
Array (  => Array ( [key1] => a1 [key2] => a2 [key3] => a3 )  => Array ( [key1] => b1 [key2] => b2 [key3] => b3
Answered By – Nigel Ren