简体   繁体   English

PHP - MySQL从产品表创建树视图

[英]PHP - MySQL create a tree view from product table

I have a category table as follows. 我有一个类别表如下。 Which I am saving category, subcategories in that table ( Multiple sub-categories ). 我在该表中保存类别,子类别(多个子类别)。 My table looks like 我的桌子看起来像

id     |    name       |  parent_of    |   created_on
-------+---------------+---------------+---------------------
1      |   Name 1      |  0            |  2013-05-1 00:00:00
-------+---------------+---------------+---------------------
2      |   Name 2      |  0            |  2013-05-1 00:00:00
-------+---------------+---------------+---------------------
3      |   Name 3      |  1            |  2013-05-1 00:00:00
-------+---------------+---------------+---------------------
4      |   Name 4      |  1            |  2013-05-1 00:00:00
-------+---------------+---------------+---------------------
5      |   Name 5      |  3            |  2013-05-1 00:00:00
-------+---------------+---------------+---------------------
6      |   Name 6      |  3            |  2013-05-1 00:00:00
-------+---------------+---------------+---------------------

Now I need to query this table and create a tree structure as follows to make a easy navigation through categories in front end. 现在,我需要查询此表并创建一个树结构,如下所示,以便轻松浏览前端的类别。

A tree like follows 一棵树如下

1
  |--> 3
  |   |--> 5
  |   |--> 6
  |--> 4
2

I am bit confused about the query. 我对查询感到有点困惑。 Can anyone please help me ? 谁能帮帮我吗 ?

Thanks in advance 提前致谢

For basic display, you may use: 对于基本显示,您可以使用:

SELECT * FROM `Table` WHERE `parent_of` = 0;

It will give you all the root nodes. 它将为您提供所有根节点。


When user click on a node, he / she / it submits request to the server (Ajax maybe) to fetch child nodes for clicked one, like: 当用户单击某个节点时,他/她/它会向服务器提交请求(可能是Ajax)以获取点击的节点的子节点,如:

$node = abs((int)$_GET['node']);

then: 然后:

SELECT * FROM `Table` WHERE `parent_of` = {$node};

Please try the below code logic for your solution, 请为您的解决方案尝试以下代码逻辑,

$result = mysql_query("SELECT id, parent_of FROM category WHERE parent_of > 0");

$treeStructure = array();
while($row = mysql_fetch_array($result)) {
    $id = $row['id'];
    $parentID = $row['parent_of'];
    $treeStructure[$parentID][] = $treeStructure[$id];                
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM