0

I have

$arr=array(array(1,2,3),
           array(4,5,6),
           array(7,8,9),
           array(10,11,12))

I need to display it in this order using for loop: 1,4,7,10,2,5,8,11,3,6,9,12. I have been busting my head for last two days on this, can anyone help me? Thanks

2
  • Are the inner arrays of the same length (always 3)? Also, you should share what you tried. Commented Nov 17, 2019 at 21:33
  • Yes they are always the same length. I have been trying something like this for($i = 0; $i < count($arr); $i++) { for($u = 0; $u <count($arr[$i]); $j++) { echo $arr[$i][$u]; echo '<br />'; } } Commented Nov 17, 2019 at 21:55

3 Answers 3

1

Something like following might help

for($i = 0; $i < 3; $i++) {
    for($j = 0; $j < 4; $j++) {
        echo $arr[$j][$i];
    }
}

You effectively cycle through 3 columns ($i) and 4 rows ($j) and reference the appropriate $arr elements.

If you wanted to use a more dynamic (count) based solution, you would use e.g:

$count = count($arr);

for($i = 0; $i < 3; $i++) {
    for($j = 0; $j < $count; $j++) {
        echo $arr[$j][$i];
    }
}

updated demo

note: it is more efficient to count() outside the for loop, so you only call the function once and use the result inside the loop.

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

2 Comments

How can that be done with count($arr) in case i want to add some more information in those arrays later on?
@lovelace Your edit isn't right. $arr corresponds to the $j index in this case. Should just be for ($j = 0; $j < $count; $j++).
0

This simple solution apply to use non-predefined length of the main array and its child:

$arr=array(array(1,2,3),
    array(4,5,6),
    array(7,8,9),
    array(10,11,12));

$count_arr = count($arr);       // length of the main array
$count_arr_arr = count($arr[0]);// length of the child array (each child should be the same length)
$res_arr = [];

for($i = 0; $i < $count_arr_arr; $i++){
    for($j = 0; $j < $count_arr; $j++){
        $res_arr[] = $arr[$j][$i];        // getting elements from child arrays 
    } 
}

echo join(', ', $res_arr);                // presenting the result as a string '1, 2, 3, etc.'

Demo

Comments

0

You can use loop nesting for that. So iterate through the array and increase the index of the column on each outer loop. Store the values in a new array for proper output.

$arr=array(array(1,2,3),
array(4,5,6),
array(7,8,9),
array(10,11,12));

$new = [];
$i = 0;

foreach($arr as $set) {
    foreach($arr as $data) {
        if(isset($data[$i])) $new[] = $data[$i];
    }
    $i++;
}

echo join(',', $new), PHP_EOL;

1,4,7,10,2,5,8,11,3,6,9,12

Comments

Your Answer

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