每4条记录创建一个列表

时间:2014-05-18 03:28:08

标签: php mysql

我正在尝试创建包含每个列表4条记录的多列记录,而不知道有多少条记录。但是,我无法弄清楚如何处理数学。我手动输入$ n == 5 || $ n == 9等知道它是必须的,并不能完全解决问题。任何人都可以帮我解决这个问题。此外,只有当记录总数不能均匀地除以4时,下面的列表才能正常工作。如果可以,它将在最后创建一个空白列表。

$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 1
$row_cnt = $result->num_rows;
$total_lists = round($row_cnt / 4, 0);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
    while ($row = $result->fetch_assoc()) {
    echo "<li>$row['something']</li>";
        if ($n == 5 || $n == 9 || $n == 13 || $n == 17 || $n == 21 || $n ==25 || $n ==29 || $n == 33 || $n == 37 || $n == 41 || $n == 45 || $n == 49 || $n == 53 || $n == 57 || $n == 61 || $n == 65 || $n == 69 || $n == 73 || $n == 77){
        echo "</ul>";
        $current_list = $current_list + 1;
        echo "<ul>List $current_list of $total_lists";
        }
    $n = $n + 1;
    }
echo "</ul>";
}

提前感谢您的帮助。 :)

解决:

$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 0
$row_cnt = $result->num_rows;
$total_lists = ceil($row_cnt / 4);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
    while ($row = $result->fetch_assoc()) {
        $n++;
    echo "<li>$row['something']</li>";
        if ($row_cnt > 4) {
    if ($n % 4 === 0) {
    echo "</ul>";
    $current_list = $current_list + 1;
    echo "<ul>List $current_list of $total_lists";
        }
        }
    }
echo "</ul>";
}

2 个答案:

答案 0 :(得分:2)

你实际上并没有偏离你想要做的事情,你只需要使用一个额外的工具来完成它:%或模数运算符。

模数运算符将返回除法问题的剩余部分:

$x = 5 % 2; // 1

看看你的逻辑,当你的增量器($n)减1除以4时,你的行动需要采取余下的0:

if (($n - 1) % 4 === 0)
{
    //your <ul> insertion could go here.
}

这是PHP手册页的链接,讨论数学运算符:

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

答案 1 :(得分:0)

或者,您可以在数据库结果上使用简单的array_chunk()。提供适当的分组(在这种情况下为四个),然后通过foreach循环它们。考虑这个例子:

// dummy data (values from db)
$values_from_db = array(
    array('id' => 1, 'something' => 'list1'),
    array('id' => 2, 'something' => 'list2'),
    array('id' => 3, 'something' => 'list3'),
    array('id' => 4, 'something' => 'list4'),
    array('id' => 5, 'something' => 'list5'),
    array('id' => 6, 'something' => 'list6'),
    array('id' => 7, 'something' => 'list7'),
    array('id' => 8, 'something' => 'list8'),
    array('id' => 9, 'something' => 'list9'),
);

$values_from_db = array_chunk($values_from_db, 4); // group them by four's

?>

<?php foreach($values_from_db as $key => $value): ?>
    <ul style="list-style-type: none;">
    <?php foreach($value as $index => $element): ?>
        <li><?php echo $element['id'].'.'.$element['something']; ?></li>
    <?php endforeach; ?>
    </ul>
<?php endforeach; ?>