gpt4 book ai didi

php - MySQL 按类别输出并分页

转载 作者:行者123 更新时间:2023-11-30 00:09:24 25 4
gpt4 key购买 nike

我有一个数据库:

category | title   | other fields...
cat1 | title1 | other fields...
cat1 | title2 | other fields...
cat1 | title3 | other fields...
cat1 | title4 | other fields...
cat2 | title5 | other fields...
cat2 | title6 | other fields...
cat2 | title7 | other fields...
cat3 | title8 | other fields...

等等...

我想输出整个表格,但将所有内容分组。所以输出看起来像:

<div class="category">
<h1>cat1</h1>
<div class="item">title1</div>
<div class="item">title2</div>
<div class="item">title3</div>
<div class="item">title4</div>
</div>
<div class="category">
<h1>cat2</h1>
<div class="item">title5</div>
<div class="item">title6</div>
<div class="item">title7</div>
</div>
<div class="category">
<h1>cat3</h1>
<div class="item">title8</div>
</div>

等等...

执行此操作的最佳方法是什么?我第一次尝试这样做,我浏览了每个条目,将其类别与最后一个条目进行比较。然而,这种方法确实有效,但事实证明它很复杂,尤其是当需要尝试实现分页时。我的下一个想法是有某种嵌套的 foreach 循环,外部用于类别,内部用于项目。这能以某种方式起作用吗?实现分页时它会起作用吗?感谢您的帮助!

最佳答案

使用 GROUP BYWITH ROLLUP 修饰符可能有助于区分类别:

SELECT category, title,  count(*) 
FROM pages
GROUP BY category,title WITH ROLLUP;

这将输出如下内容:

category | title   | other fields... | count
cat1 | title1 | other fields... | 1
cat1 | title2 | other fields... | 1
cat1 | title3 | other fields... | 1
cat1 | title4 | other fields... | 1
cat1 | NULL | last other fields... | 4
cat2 | title5 | other fields... | 1
cat2 | title6 | other fields... | 1
cat2 | title7 | other fields... | 1
cat2 | NULL | last other fields... | 3
cat3 | title8 | other fields...
cat3 | NULL | last other fields... | 1
NULL | NULL | last other fields... | 8

现在您可以看到,如果标题为空,则您已到达类别的末尾。您还可以查看特定分页类别中有多少页面。

关于php - MySQL 按类别输出并分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24211334/

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