1

I have 3 arrays:

array(1, 5, 1);
array(3, 2, 7, 5 ,4);
array(4, 3, 6, 5)

I want to merge them and get such result:

array(
    array(1, 3, 4),
    array(5, 2, 3),
    array(1, 7, 6),
    array(5, 5),
    array(4)
);

What is the easiest way?

1

4 Answers 4

5
$arrs = array(
  array(1, 5, 1),
  array(3, 2, 7, 5, 4),
  array(4, 3, 6, 5),
);

$result = array();
$num_arrs = count($arrs);
for($i = 0; $i < $num_arrs; $i++){
  $size = count($arrs[$i]);
  for($j = 0; $j < $size; $j++){
    if(!isset($result[$j]))
      $result[$j] = array();
    $result[$j][] = $arrs[$i][$j];
  }
}

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

.push() in PHP? What is it?
@VahidHallaji Mixed up languages with Javascript. I've edited since then though
Good solution, thanks, but @Kolink solution is a little bit simpler.
3

Assuming you have the latest version of PHP (5.5), you can use this:

$input = array(
    array(1,5,1),
    array(3,2,7,5,4),
    array(4,3,6,5)
);
$output = array_column($input,null);

If you don't have the latest version, see the original PHP version for a shim.

Alternatively, for this specific case (ie. a specialised shim), try this:

$input = array(...); // see code block above
$output = array();
foreach($input as $arr) foreach($arr as $i=>$v) $output[$i][] = $v;

1 Comment

Nice! Directly what I want!
1
$arrays = array(
  array(1, 5, 1),
  array(3, 2, 7, 5 ,4),
  array(4, 3, 6, 5)
);
$combined = array();
foreach($arrays as $array) {
  foreach($array as $index => $val) {
     if(!isset($combined[$index])) $combined[$index] = array();
     $combined[$index][] = $val;
} }

After that $combined holds what you want.

1 Comment

Good solution, thanks, but @Kolink solution is a little bit simpler.
1

Is this what you want?
You can use array_map

<?php
  $a  = array( 1, 5, 1 );
  $b  = array( 3, 2, 7, 5 ,4 );
  $c  = array( 4, 3, 6, 5 );

  $d  = array_map( function() {
    return array_filter( func_get_args() );
  }, $a, $b, $c );

  print_r( $d );
?>

Output

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 4
        )

    [1] => Array
        (
            [0] => 5
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 7
            [2] => 6
        )

    [3] => Array
        (
            [1] => 5
            [2] => 5
        )

    [4] => Array
        (
            [1] => 4
        )

)

1 Comment

Good solution, thanks, but @Kolink solution is a little bit simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.