duancan1950 2012-04-01 13:12
浏览 21
已采纳

按其他表格的标题对结果进行分组

I have two tables, one contains the page/heading number and the heading text, the other contains values to print under each heading:

Headings:

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

Contents:

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

I want the results for page 1 to be:

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

Augmented with HTML where needed.

Using two while loops with mysql_fetch_array() doesn't work because you have to fetch before you can check if it's under the correct heading. This means I miss the first entry of every next heading.

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

Is there any way to do this without running multiple queries for every heading? (There may be many on a page)

  • 写回答

2条回答 默认 最新

  • duanmu3049 2012-04-01 13:23
    关注

    Just fetch all results into 2 arrays before iterating with while loops.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败