如何从数据库中获取多维数组?
我知道标题可能不完全是这个意思,但请耐心等待。 我不知道如何给这个起另一个标题。
好吧,看看这就是我的情况。 我正在构建一个小型cms系统(为我自己并从中学习)。我希望 CMS 内的页面按类别列出和排序。 它看起来像这样:
Webpages
- Home
-- homepage(this is the web page itself)
- News
-- Latest news
-- Archive
这个系统意味着我将有子类别。
在数据库中,我制作了一个表格:
| ID | Parent_ID | Name | Lable | Order|
1 1 Webpages webpages 1
2 1 Home home 1
3 1 News news 2
正如您在此处看到的,主要类别是网页类别,主页和新闻是它的子类别。 这两个类别是有序的,因此“主页”类别排在第一位,然后是“新闻”类别。
我面临的问题是这样的: 如果我想获取所有子类别,则意味着我需要从主类别网页开始,通过该 ID,我可以获得主类别的子类别。
我想你可以看到这可以有多深,这意味着(我认为)最终将为每个子类别运行许多查询。
所以我的问题是: 有没有一种方法可以在一个 ore 2 查询中以正确的顺序一次性获取所有子类别。
如果您有答案,请告诉我。
谢谢
I know the title may not be exactly what this is about but bear with me.
I don't know how another title for this.
Well look this is my situation.
I'm building a little cms system (for myself and to learn from it). I want the pages inside the CMS to be listed and ordered by categories.
It will look something like this:
Webpages
- Home
-- homepage(this is the web page itself)
- News
-- Latest news
-- Archive
this system would mean I will have sub-categories.
In the database I have made a table:
| ID | Parent_ID | Name | Lable | Order|
1 1 Webpages webpages 1
2 1 Home home 1
3 1 News news 2
As you can see here the main category is the Webpages category and Home and News are sub-categories of it.
And those 2 categories are ordered so the Home category is first then the News second.
The problem I'm facing is this:
If i want to get all the sub-categories means i need to start with the main category Webpages and with that ID i can get the sub-categories of the main category.
I think you can see how deep this can go en that would mean (I think) that there will eventually be many query's that will be run for each sub-category.
So my question is:
Is there a way to get all the sub-categories at once in the correct order in one ore 2 query's.
if you have an answer, please let me know.
thnks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编写查询时,您需要使用 ORDER BY 子句。对于此特定示例,您将需要 ORDER BY Parent_ID、Order。这将返回按 Parent_ID 排序,然后按 Order 进行子排序。
然后,您可以使用 mysql_fetch_assoc() 将结果集解析为关联数组。
由于您将具有多个层次结构,因此一旦将结果集存储在由层次结构组成的关联数组中,您就必须循环遍历结果集。
然后可以使用该数组在页面上显示适当的导航层次结构。
When writing the query you will need to use the ORDER BY clause. For this specific example you will need to ORDER BY Parent_ID, Order. This will return sorted by Parent_ID and then sub sorted by Order.
You can then use mysql_fetch_assoc() for parse the result set into an associative array.
Since you are going to have multiple levels of hierarchy you will have to loop through the result set once store it in a associative array consisting of the hierarchy structure.
This array can then be used to display the appropriate navigation hierarchy on the page.