Jump to content

Putting a div around every 4 database items


White_Lily

Recommended Posts

Hey,

 

I have a database full of "Depots" and basically instead of just one straight contact form on this clients website, they want a list of each of their depots on the contact page instead with individual phone numbers and locations, etc.

 

What I was wondering is, is there a way with php where I can basically say:

 

"For every 4 entries listed, put one large div around them"?

 

So far there are 13 depots listed, but there are 4 depots for every row on their website.

 

any ideas?

When you loop though the results, you should add a condition and incriment variable. Something like this :

$i = 0;
<?php foreach($db_res as $value) : ?>

  <?php if($i == 4) : ?>
      <?php $ = 0; ?>
      <div class="something"><?php echo $value->something; ?></div>
  <?php else : ?>
      <?php echo $value->something; ?>
  <?php endif; ?>

<?php endforeach; ?>

Sorry about ugly formatting, this is one bad editor :-\

Or you can try doing it in one clean script. This is somewhat the same script as gmaestroo's but... cleaner

 

<?php

$i = 0;

foreach($db_res as $value)
{
  if ($i == 0)
  {
      echo '<div class="something">';
  }

  echo $value['some_key_name'];

 if ($i == 4)
  {
      echo '</div>';

      $i = 0; // reset to 0 for future rows.
  }

   ++$i;
}

?>

 

I havent tested the script but the logic is there. Also, if the number of rows is not exactly x*4 this script will fail to add the last </div>. Im sure you can figure that out.

Both answers lacked a check if the results are not a multiple of 4.

 

If you put 13 results, you get an open div round the last result, but not a closing one.

 

Try this:

 

<?PHP
 
  $num = 0;
 
  $output = '';
 
  foreach($db_res as $value) { $num++;
    //### Open div
    if($num%4==1) {
      $output .= '<div>';
    }
    
    //### Add value to output
    $output .= $value;
    
    //### Close div
    if($num%4 == 0) {
      $output .= '</div>';
    }
      
  }
 
  //### If total results is not multiple of 4, close the final div
  if($num%4 != 0) {
    $output .= '</div>';
  }
 
  //### Display output
  echo $output;
 
?>
  On 3/22/2013 at 12:55 PM, DaveyK said:

I havent tested the script but the logic is there. Also, if the number of rows is not exactly x*4 this script will fail to add the last </div>. Im sure you can figure that out.

 

I totally missed this, I don't know how I manage to do that. Davey pointed out the error for the final div closing, kudos.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.