将结果分组到一个标题下 [英] Grouping results under a heading

查看:96
本文介绍了将结果分组到一个标题下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能真的很明显和简单-但这并不是我的基本知识:)

This is probably really obvious and simple - but it isn't to me with my rudimentary knowledge:)

我有两个桌子:

table_items
-----------
item_id ¦ item_name ¦ item_describtion ¦ more item stuff.....

table_subitems
-----------------
subitem_id ¦ item_id ¦ subitem_name ¦ More subitem stuff

每个项目可以有零个到几乎无限的子项目,并且与item_id字段相关.

Each item can have zero to pretty much unlimited subitems, and are related by the fields item_id.

我要打印出按项目分组的子项目.

I want to print out the subitems grouped by item.

我目前正在使用查询来执行此操作,该查询选择table_items.item_id = table_subitems.item_id所在的子项目,然后使用while循环显示它们,就目前而言,这很好,我得到的是这样的东西:

I am currently doing this with a query which selects subitems where table_items.item_id = table_subitems.item_id and then displays them with a while loop, which is fine as far as it goes, I get something like this:

Item One
========
Subitem 0ne

Item One
========
Subitem two

Item One
========
Subitem three

Item Two
========
Subitem one

Item Three
==========
Subitem one

Item Three
==========

 Subitem two

但是我想要

ITEM ONE
--------
Subitem one
Subitem two
Subitem three

ITEM TWO
--------
Subitem one

ITEM THREE
----------
Subitem one
Subitem two

我该怎么做?它是查询的功能还是我如何显示结果的功能?

How do I do this? Is it a function of the query or of how I show the results?

我对PHP的了解在增长,但仍然很有限,我正在以一种程序性的方式来做到这一点(即,不是OOP,这是我试图掌握但还没有完全解决的问题),所以请像我一样愚蠢地与我交谈

My knowledge of PHP is growing but still limited, and I'm doing this in a procedural way (ie it's not OOP, which I am trying to grasp but haven't fully) so talk to me like I'm stupid.

推荐答案

使用保存最后一个标题的变量,并且仅当当前标题与最后一个不同时才打印当前标题:

Use a variable that holds the last heading and print the current heading only if it differs from the last:

$last = null;
while ( /* … */ ) {
    if ($row['item_id'] != $last) {
        echo '<hx>'.$row['item_name'].'</hx>';
        $last = $row['item_id'];
    }
    echo $row['subitem_name'];
}

这篇关于将结果分组到一个标题下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆