gpt4 book ai didi

php - 如何根据项目的组和数量生成列?

转载 作者:行者123 更新时间:2023-11-29 16:34:30 24 4
gpt4 key购买 nike

我有不同类别的数据。例如:沙拉、甜点

我想根据类别对它们进行分组,并且每列仅包含 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>";
}

}

最佳答案

尝试像下面这样分割数组:

$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";
}
}

关于php - 如何根据项目的组和数量生成列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53697718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com