按列表循环分组

时间:2015-11-26 23:59:56

标签: php

我在我的数据库的表中有100个位置记录,我需要例如用ul列表划分4列,其中每个ul /列有25条记录,但是我还没有完全使用它,这是我的代码:

$sql = "SELECT * FROM districts";
$consulta = mysql_query($sql);
$beginTag = '
    <div class="four columns">
        <h4>&nbsp;</h4>
        <ul class="footer-links">';

$endTag = '</ul></div>';
$html = '';

$counter = 4;
if ($counter >= 4) {
    echo $beginTag;
}

while ($mostrar = mysql_fetch_array($consulta)) {
    $counter++;
    $town = $mostrar['name_en'];                

    echo '<li><a href="#"><strong>'.$town.'</strong> Jobs</a></li>';            

    $counter = 0;

}

if ($counter >= 4) {
    echo $endTag;
}

2 个答案:

答案 0 :(得分:0)

请注意,mysql_*函数已弃用,因此您应使用mysqli_*或PDO。 以下代码将生成四个ul 25 li。使用CSS,您可以将这些ul对齐在四列中。 否则,每个人可以有25 ulli,以达到同样的效果。

$connection = mysqli_connect('your_server', 'your_username', 'your_password', 'your_database');
if (!$connection) {
    echo mysqli_connect_errno();
}

$sql = "SELECT * FROM districts";
$consulta = mysqli_query($connection, $sql);
$beginTag = '
    <div class="four columns">
        <h4>&nbsp;</h4>
        <ul class="footer-links">';

$i = 0;

while ($mostrar = mysqli_fetch_array ($consulta)) {
    $town = $mostrar['name_en'];                
    if ($i % 25 == 0) {
        echo '</ul><ul>';
    }
    echo '<li><a href="#"><strong>'.$town.'</strong> Jobs</a></li>';
    $i++;
}

echo '</ul></div>';

答案 1 :(得分:0)

您的代码存在一些问题:计数器会在每个循环中重置,因此永远不会达到最大值,并且循环中不会输出$beginTag$endTag

您可以通过从db查询中获取行数来计算每列的行数,以便在将来行数更改时代码仍然有效。

您还应该使用mysqli,因为MySQL扩展已被弃用多年,即将在即将发布的PHP7版本中删除。

// assumes your mysqli_connect on $con
$sql = "SELECT * FROM districts";
$consulta = mysqli_query($con, $sql);

$beginTag = '
    <div class="four columns">
        <h4>&nbsp;</h4>
        <ul class="footer-links">';
$endTag = '</ul></div>';
$html = '';
// calculate the max rows per column
$cols = 4;
$max = ceil(mysqli_num_rows($consulta) / $cols);
$counter = 0;
while ($mostrar = mysqli_fetch_assoc($consulta)) {
  // check for first row to output the beginTag
  if ($counter == 0) {
    echo $beginTag;
  }
  $town = $mostrar['name_en'];
  echo '<li><a href="#"><strong>'.$town.'</strong> Jobs</a></li>';            
  $counter++;
  // check for max per column
  if ($counter >= $max) {
    echo $endTag;
    // reset the counter
    $counter = 0;
  }
}