tags:

views:

112

answers:

4

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.

+3  A: 

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?

Aillyn
What do you mean "with an arbitrary number of arrays"? `array_map` accepts an arbitrary number of arrays,
Artefacto
@Artefacto You are right I guess. Now that I think about, I don't know what I meant.
Aillyn
A: 

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];
  }
}
silvo
The prefix `++` is evil and apparently confusing you, silvo. Array indices start at `0`.
You
@You: In c++/C# it does not matter if pre or post increment is used in the for loop. Do you want to say that it matters in php? I think you are mistaken.
silvo
@Aillyn: Give me a chance to upskill myself. What exactly is incorrect there?
silvo
@silvo Your previous answer didn't work. This one still has problems. Try and use it with the OP's inputs. I removed my downvote though.
Aillyn
@Aillyn: Spotted the missing $s. Thanks.
silvo
@You - preincrement is good. It is slightly faster than post increment in PHP. In this case using either would give the same result.
Peter Ajtai
A: 

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
       )
)
Zane Edward Dockery
This is not what the OP wants.
pessimopoppotamus