我有不同类别的数据。 例如:沙拉,甜点
我想根据类别对它们进行分组,每列也只能包含5个项目。
<div>
<h3>Salads</h3>
<div>
salad 0
salad 1
salad 2
salad 3
salad 4
</div>
<div>
salad 5
salad 6
salad 7
salad 8
salad 9
salad 10
</div>
<div>
salad 11
</div>
</div>
<div>
<h3> Desserts</h3>
<div>
Dessert 1
Dessert 2
Dessert 3
Dessert 4
Dessert 5
</div>
<div>
Dessert 6
</div>
</div>
如何使用php实现它?需要帮忙。预先感谢。
这是我正在使用的代码。此代码的问题是,如果类别的项目数为偶数,则该类别不起作用。如果项目数量奇数,那么它完全可以正常工作。
$itemsperrow = 2;
$sql_menugrouptbl = "SELECT category FROM ck_menulist GROUP BY category ORDER BY id";
$result = $conn->query($sql_menugrouptbl);
$result->execute();
echo "Total category: ". $result->rowcount();
foreach($result as $row){
$categ = $row['category'];
$sql_menulisttbl = "SELECT * FROM ck_menulist WHERE category = '$categ'";
$stmt = $conn->Prepare($sql_menulisttbl);
$stmt ->execute();
$countmenulist = $stmt->rowcount();
echo "<h1>".$categ." (".$countmenulist.")</h1>";
foreach($stmt as $rowitem){
if ($countmenulist % $itemsperrow == 1)
{
echo "<div class=\"col-md-4 jt_col column_container\">";
echo "<div class=\"voffset10\"></div>";
echo "<ul class=\"menu\">";
}
echo "<li>";
echo $rowitem['itemname'];
echo "<div class=\"detail\">".$rowitem['itemdescription']." <span class=\"price\">$ ".$rowitem['price']."</span></div>";
echo "</li>";
if ($countmenulist%$itemsperrow == 0)
{
echo "\n";
echo "</div>";
echo "\n";
}
$countmenulist++;
}
if ($countmenulist%$itemsperrow != 1) {
echo "\n";
echo "</div>";
}
}
答案 0 :(得分:0)
尝试按如下所示拆分数组:
$sql_menugrouptbl = "SELECT category FROM ck_menulist GROUP BY category ORDER BY id";
$result = $conn->query($sql_menugrouptbl);
$result->execute();
echo "Total category: ". $result->rowcount();
foreach($result as $row){
$categ = $row['category'];
$sql_menulisttbl = "SELECT * FROM ck_menulist WHERE category = '$categ'";
$stmt = $conn->Prepare($sql_menulisttbl);
$stmt ->execute();
$countmenulist = $stmt->rowcount();
echo "<h1>".$categ." (".$countmenulist.")</h1>";
$splitted_item = array_chunk($stmt, $itemsperrow, true);
foreach($splitted_item as $sub_menu){
echo "<div class=\"col-md-4 jt_col column_container\">";
echo "<div class=\"voffset10\"></div>";
echo "<ul class=\"menu\">";
foreach($sub_menu as $rowitem){
echo "<li>";
echo $rowitem['itemname'];
echo "<div class=\"detail\">".$rowitem['itemdescription']." <span class=\"price\">$ ".$rowitem['price']."</span></div>";
echo "</li>";
}
echo "</ul>";
echo "\n";
echo "</div>";
echo "\n";
}
}