0

I've got an (php) array with, 1, 2, 3, 4, 5 or 6 results. I want to display them as following in the different situations:

1 result:

[result 1]

2 results:

[result 1]  [result 2]

3 results:

[result 1]  [result 3]
[result 2]

4 results:

[result 1]  [result 3]
[result 2]  [result 4]

5 results:

[result 1]  [result 4]
[result 2]  [result 5]
[result 3]

6 results:

[result 1]  [result 4]
[result 2]  [result 5]
[result 3]  [result 6]

It would be nice if I could this with CSS only (and not with tables of course), so the right order is preserved in the source, but the display goes as above. Otherwise I think I need some weird PHP loop to get these results in the right order on my screen. Anybody know how to do this? Thanks in advance!

Joris Portfolioris
  • 141
  • 1
  • 1
  • 10

3 Answers3

0

It guess it's not possible to do something with css only. You will have to split your array in two and display the first half to the first column and the second half to the second column. Should not be very hard to do?

Yann Sagon
  • 547
  • 3
  • 21
0

Something like

$out = "<table><tbody>";
for ($i = 0; $i < count($array); $i++){
    $el = $array[$i];
    if(($i % 2) === 0){
        $out .= '<tr>';
    }
    $out .= "<td>$el</td>";
    //Handlethe case that this is the last iteration and 
    //the elements of the array are odd
    if((($i % 2) === 1) && (($i + 1) === count($array))){
        $out .= "<td></td></tr>";
    }elseif(($i % 2) === 1){
        $out .= "</tr>";
    }
}

$out .= "</tbody></table>";
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
0
$array = array( 1, 2, 3, 4, 5, 6, 7 );

$number_of_columns = floatval(2.0); // float to make the below ceil work
$number_of_items = count( $array );
$items_per_column = ceil( $number_of_items / $number_of_columns );
$current_column = 0;

for ( $i = 0; $i < $number_of_items; $i++ ){

    if ( $i % items_per_column == 0 ){ 
        $current_column++;
    }

    echo $i, ' -> ', $current_column, '<br />';
}   
scibuff
  • 13,377
  • 2
  • 27
  • 30