Reputation: 11
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,
),
)
Upvotes: 1
Views: 607
Reputation: 47992
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,
),
)
Upvotes: 0
Reputation: 152266
Try with:
$length = sizeof($arrayA);
$output = array();
for ( $i = 0; $i < $length; ++$i ) {
$output[] = array_combine($arrayA[$i], $arrayB[$i]);
}
Upvotes: 4