Quick example: array_1 = 1, 2, 3; array_2 = a, b, c and array_3 = white, red, blue.
I need an array like array_4 = ((1,a,white), (2,b,red), (3,c,blue)).
I hope I'm not being to confusing. Thanks in advance.
Quick example: array_1 = 1, 2, 3; array_2 = a, b, c and array_3 = white, red, blue.
I need an array like array_4 = ((1,a,white), (2,b,red), (3,c,blue)).
I hope I'm not being to confusing. Thanks in advance.
You mean something like Python's zip()? This will do:
$zipped = array_map(null, $array_1, $array_2, $array_3);
If you want a function that can do it with an arbitrary number of arrays, see: Is there a PHP function like Python's zip?
I guess you are looking for a one-liner? I can't provide that, but this is my attempt:
$array_4=array();
for($i = 0 ; $i<count($array_1) ; ++$i) {
$array_4[$i] = array($array_1[$i], $array_2[$i], $array_3[$i]);
}
This code of course assumes that all input arrays have the same lengths.
If you have more than 3 input arrays I would put them all in an array and foreach over it:
$all_arrays = array($aray_1, $array_2, ...);
$output_array=array();
for($i = 0 ; $i<count($array_1) ; ++$i) {
$output_array[$i] = array();
foreach($all_arrays as $input_array) {
$output_array[$i][] = $input_array[$i];
}
}
I think the easiest way, without using a bunch of array_X functions would be to simply "concatenate" them all into one array.
For instance
$arr1 = array(1,2,3);
$arr2 = array(a,b,c);
$arr3 = array("red","white","blue");
$bigArray[] = $arr1;
$bigArray[] = $arr2;
$bigArray[] = $arr3;
Then you would have 1 Array containing three separate arrays, assuming that is what you're after.
$bigArray would look something like this
Array (
0 Array (
0 => 1
1 => 2
2 => 3
)
1 Array (
0 => a
1 => b
2 => c
)
2 Array (
0 => red
1 => white
2 => blue
)
)