tags:

views:

48

answers:

3

Let's say I have a user that entered 12 links into the database but when they are displayed I want to break up the links into groups of 3 and repeat the groups of three until all 12 kinks are displayed for example.

<div>
 <p><a href="">Link 1</a></p>
 <p><a href="">Link 2</a></p>
 <p><a href="">Link 3</a></p>
</div>

Here is part of the code I'm working with. How should my code look like?

while ($row = mysqli_fetch_assoc($dbc)) {
  if (!empty($row['category']) && !empty($row['url'])) {
    echo '<div>';
    echo '<p><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p>';
    echo '</div>';
 }

}
+1  A: 

Something like this gets you three links per div. We add the extra conditional echo at the end for the case that there's not a multiple of 3 links

$ctr = 0;
while ($row = mysqli_fetch_assoc($dbc)) {
    if (!empty($row['category']) && !empty($row['url'])) {
        if ($ctr%3 == 0) {
            echo '<div>';
        }
        $ctr ++;
        echo '<p><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p?';
        if ($ctr%3 == 0) { 
            echo '</div>';
        }
    }

}
if ($ctr%3 != 0) { 
  echo '</div>';
}
mabwi
A: 

if you want to avoid incrementing/resetting i every time you reach three, you can just use the modulus operator:

http://php.net/manual/en/language.operators.arithmetic.php

Something like:

if( $i%3 == 0 ){
  // divisible by 3...
}
AJ
A: 

An easier method would be more like:

while(true) {
    $c = 0;
    echo "<div>";
    while ($row = mysqli_fetch_assoc($dbc) && $c++ < 3) {
     if (!empty($row['category']) && !empty($row['url'])) {
      echo '<p><a href="' . $row['url'] . '" title="' . $row['category'] . ' Category Link">' . $row['category'] . '</a></p>';
     }
    }
    echo "</div>";
    if(empty($row))
     break;
}
mattbasta