php - 按其他表中的标题对结果进行分组

标签 php mysql sql

我有两个表格,一个包含页码/标题编号和标题文本,另一个包含要在每个标题下打印的值:

标题:

page | heading | text
1    | 1       | "heading 1"
1    | 2       | "heading 2"

内容:

page | heading | contents
1    | 1       | "some stuff"
1    | 1       | "some more stuff"
1    | 2       | "some other stuff"

我希望第 1 页的结果为:

heading 1
some stuff
some more stuff
heading 2
some other stuff

在需要的地方使用 HTML 进行增强。

mysql_fetch_array() 中使用两个 while 循环不起作用,因为您必须先获取数据,然后才能检查它是否位于正确的标题下。这意味着我错过了每个下一个标题的第一个条目。

$query = "SELECT text,heading FROM headings WHERE page=".$page." ORDER BY heading ASC";
$headings = mysql_query($query) or die(mysql_error());
$query = "SELECT filename,heading FROM pictures WHERE page=".$page." ORDER BY heading ASC";
$pictures = mysql_query($query) or die(mysql_error());

while($heading = mysql_fetch_array($headings)){
echo $heading[0];
    while($image = mysql_fetch_array($pictures)){ # This skips entries because I have to check the contents themselves
        if($image[1] != $heading[1]){
            break;
        }
        echo $image[0];
    }
}

有没有办法在不为每个标题运行多个查询的情况下执行此操作? (一页上可能有很多)

最佳答案

只需在使用 while 循环进行迭代之前将所有结果提取到 2 个数组中即可。

关于php - 按其他表中的标题对结果进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9964653/

相关文章:

php - Laravel - 干预图像 - 图像源不可读

php - 将MySQL日期时间转换为不同时区

android - 如何使用数据库数据分发 Android 应用程序?

python - 使用 Peewee ORM 生成图表数据

python - 将 int 转换为时间戳或任何日期格式 sql

php - Laravel Valet php-fpm已经在代客 socks 上听了

php - 未捕获的类型错误 : Cannot read property JSON

javascript - 使用 .getJSON 为条件 SQL 查询传递变量

mysql - 在列中显示具有重复值的记录的第一个实例

javascript - 忽略其中包含公式的空单元格值