开发者

Combine 3 or more arrays (php) [duplicate]

This question already has answers here: Transposing multidimensional arrays in PHP 开发者_开发技巧 (12 answers) Closed 9 months ago.

Quick example:

$array_1 = [1, 2, 3];
$array_2 = ['a', 'b', 'c'];
$array_3 = ['white', 'red', 'blue'];

I need an array like:

$array_4 = [
    [1, 'a', 'white'],
    [2, 'b', 'red'],
    [3, 'c', 'blue']
]


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];
  }
}


You question is not very clear but:

If you want to combine all the values of 3 or more arrays into one array you can do this:

$array_4 = array_merge($array_1, $array_2, $array_3);

If you want to combine all those arrays into one you can do this:

$array_4[] = $array_1;
$array_4[] = $array_2;
$array_5[] = $array_3;

But I think you are really after for what Silvo posted above, hence +1 to him.


Just a simple array_merge would do this.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜