我想創建多列表的記錄與每個列表4記錄而不知道有多少記錄。但是,我無法弄清楚如何處理數學。我手動輸入$ n == 5 || $ n == 9等知道它是有條件的,並不能完全解決問題。任何人都可以幫助我如何處理。而且,只有在記錄總數不能被4除以4的情況下,下面的列表才能正常工作。如果可以,它將在最後創建一個空列表。創建每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>";
}
有人聽說過模運算符:http://www.php.net/manual/en/language.operators.arithmetic.php? – CodeZombie
或者,您可以將數組結果('array_chunk()')四捨五入,然後將它們分組爲四,然後相應地循環它們。 – user1978142