array_combine() on each subarrays of two multidimensional arrays

596 Views Asked by At

In PHP, I have 2 multidimensional arrays. such as:

array 1:

[[1, 2, 3], [1, 2, 3]];

Array 2:

[[4, 5, 6], [7, 8, 9]];

I need to combine these two arrays.

I need the first array's subarray values to be the keys of resulting multidimensional's subarrays and the second array's subarray values to be the values of resulting multidimensional's subarray.

I need the output like this format:

array (
  0 => 
  array (
    1 => 4,
    2 => 5,
    3 => 6,
  ),
  1 => 
  array (
    1 => 7,
    2 => 8,
    3 => 9,
  ),
)
2

There are 2 best solutions below

0
On

Try with:

$length = sizeof($arrayA);
$output = array();

for ( $i = 0; $i < $length; ++$i ) {
  $output[] = array_combine($arrayA[$i], $arrayB[$i]);
}
0
On

This can be concisely accomplished by calling array_combine() while simultaneously iterating (mapping) the two equal-length arrays with equal-length subarrays.

Code: (Demo)

$arr1 = [[1, 2, 3], [1, 2, 3]];
$arr2 = [[4, 5, 6], [7, 8, 9]];
var_export(
    array_map('array_combine', $arr1, $arr2)
);

Output:

array (
  0 => 
  array (
    1 => 4,
    2 => 5,
    3 => 6,
  ),
  1 => 
  array (
    1 => 7,
    2 => 8,
    3 => 9,
  ),
)