简体   繁体   中英

PHP add <div “style=”clear"> </div> in a loop after every 4 records

To style a page correctly I need to add <div style="clear:both"></div> after every 4 records in a loop.

Currently every records outputted into a php file and displayed in a <div> like I have below.

<div>content</div> 

On every 4th record I would like to add a clear <div> like this:

<div>content</div>
<div style="clear:both"></div>

Use a modulos

$i = 1;
while ($row = mysql_fetch_array($result) {
    echo '<div>'.$row.'</div>';
    if (($i++ % 4) == 0) echo '<div style="clear:both;"></div>';
}

You should not use mysql as it is deprecated. Instead, use MySQLi or PDO .

Adding this to you loop body ought to do the trick

if ($i != 0 && $i % 4 == 0) 
  //Output clear div here

I suggest you to use CSS as well, for example like this:

CSS

<style type="text/css">
    .normaldiv {
        /* other stuff here */
    }
    .cleardiv {
        clear: both;
    }
</style>

PHP

$array = array(
    'data1',
    'data2',
    'data3',
    ...
    'datan'
);

$html = '';

foreach ($array as $i => $data) {
    // Add class "normaldiv" or "normaldiv cleardiv"
    $html .= '<div class="normaldiv' . ( $i%4 == 3 ? ' cleardiv' : '' ) . '">' . $data . '</div>';
}

// Do anything with your html string
echo $html;

Maybe you need to adjust it to your needs (for example using an if clause within the foreach, if you want to make an empty div without css class "normaldiv").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM