PHP - Tricky... array into columns, but in a specific order.

Posted by Joe on Stack Overflow See other posts from Stack Overflow or by Joe
Published on 2010-03-24T06:34:48Z Indexed on 2010/03/24 6:53 UTC
Read the original article Hit count: 293

Filed under:
<?php

$combinedArray = array("apple","banana","watermelon","lemon","orange","mango");


        $num_cols = 3;

        $i = 0;
        foreach ($combinedArray as $r ){
            /*** use modulo to check if the row should end ***/
            echo $i++%$num_cols==0 ? '<div style="clear:both;"></div>' : '';
            /*** output the array item ***/
    ?>
        <div style="float:left; width:33%;">
    <?php
            echo $r;
    ?>
        </div>
    <?php
        }
    ?>
    <div style="clear:both;"></div>

The above code will print out the array like this:

apple --- banana --- watermelon

lemon --- orange --- mango

However, I need it like this:

apple --- watermelon --- orange

banana --- lemon --- mango

Do you know how to convert this? Basically, each value in the array needs to be placed underneath the one above, but it must be based on this same structure of 3 columns, and also an equal amount of fruits per column/row (unless there was like 7 fruits there would be 3 in one column and 2 in the other columns.

Sorry I know it's confusing lol

© Stack Overflow or respective owner

Related posts about php