1

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,
  ),
)
0

2 Answers 2

4

Try with:

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

for ( $i = 0; $i < $length; ++$i ) {
  $output[] = array_combine($arrayA[$i], $arrayB[$i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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,
  ),
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.