PHP - Alternating rows & column output

541 views Asked by At

The principle is similar to zebra-striping a table, but it's not exactly the same thing, so I've had a tough time finding a solution / thinking about the way to do this.

I am trying to alternate the number of columns per row. Every odd row will have 4 columns and every even row will have 3.

If my query returns 11 records, I'd like to:

  1. Output the first four into 1 row, 4 columns
  2. The next three into 1 row, 3 columns
  3. The last four into 1 row, 4 columns

I posted a sample array and markup on phpfiddle to help illustrate my goal: http://phpfiddle.org/main/code/h9r-hj1

Any help is appreciated!

2

There are 2 answers

1
Chris Rasco On BEST ANSWER

Tested and working. Newlines can be relocated as per your needs.

http://codepad.org/O1BFebhC

<?php

$items[334] = array( 'name' => 'L. Dalton', 'id' => 3456921 ); 
$items[234] = array( 'name' => 'B. Harris', 'id' => 563456 ); 
$items[212] = array( 'name' => 'R. Fox', 'id' => 6879879 ); 
$items[654] = array( 'name' => 'T. Marcus', 'id' => 14234 ); 
$items[865] = array( 'name' => 'M. Kitsap', 'id' => 79087 ); 
$items[875] = array( 'name' => 'P. McDonald', 'id' => 2454662 ); 
$items[675] = array( 'name' => 'J. Harvey', 'id' => 234545 ); 
$items[343] = array( 'name' => 'G. Steinmetz', 'id' => 8578768 ); 
$items[167] = array( 'name' => 'R. Stanley', 'id' => 34234 ); 
$items[899] = array( 'name' => 'C. Morris', 'id' => 546378 ); 
$items[932] = array( 'name' => 'S. Tan', 'id' => 578758 ); 


$counter = 1;
$limit = 4;
foreach($items as $item)
{
    if($limit == 4 && $counter == 1)
    {
        ?><div class="four-up"><?php echo "\n";
    }
    else if($limit == 3 && $counter == 1)
    {
        ?><div class="three-up"><?php echo "\n";
    }

    ?><div class="col col-<?php echo $counter; ?>"> <?php echo $item['name']; ?> <br /><?php echo $item['id']; ?></div><?php echo "\n";

    if($limit == $counter)
    {
        ?></div><?php echo "\n";
        $counter = 1;
        if($limit == 3) $limit = 4;
        else if($limit == 4) $limit = 3;
    }
    else
    {
        $counter++;
    }
}
0
jko On

untested code, but it should give an idea:

for ( $c=0 ,  $cnt=count($array) ,  $m=4 ; $c<$cnt ; )  // used like a while()
{
    echo '<div class="', ($m==4 ? 'four' : 'three' ) ,'-up">';
    for ( $cm=$cnt+$m ; $c<$cm ; ++$c)
    {
      // output row 
    }
    unset($cm);
    echo '</div>';
    $m = ( $m == 4 ? 3 : 4 );
}
unset($c, $m , $cnt);