Given that I have these arrays:
$array1
:
Array
(
[0] => Title1
[1] => Title2
[2] => Title3
[3] => Title4
...
$array2
:
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
...
$array3
:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
...
I want to convert all the upper arrays into one Multidimensional Array that looks like this:
Array
(
[0] => Array
(
[0] => Title1
[1] => A
[2] => 1
)
[1] => Array
(
[0] => Title2
[1] => B
[2] => 2
)
[2] => Array
(
[0] => Title3
[1] => C
[2] => 3
)
...
I have this code that does what I want but is excessive and inefficient:
$result1 = array();
foreach($array1 as $key => $value) {
$tmp = array($value);
if (isset($array2[$key])) {
$tmp[] = $array2[$key];
}
$result1[] = $tmp;
}
$result2 = array();
$i=0;
foreach($result1 as $value){
$result2[$i] = $value;
$result2[$i][] = $array3[$i];
$i++;
}
print_r($result2);
In terms of efficiency, how can I improve my code? Can this be done all in one "foreach"? What about if I have ten or even more simple arrays? If this is the case, using my code I would have to copy down the second foreach and change the variables for each other array that comes after the first two arrays.
This should work for you:
Just use array_map()
to loop through all arrays at once, e.g.
$result = array_map(function($v1, $v2, $v3){
return [$v1, $v2, $v3];
}, $array1, $array2, $array3);
Or you can use call_user_func_array()
, so if you expand you only have to add the variables to the array and don't have to add the arguments in the anonymous function:
$result = call_user_func_array("array_map", [NULL, $array1, $array2, $array3]);
array_map()
is the way to go but it's much easier:
$result = array_map(null, $array1, $array2, $array3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With