查询选择树的所有分支 [英] query for selecting all of the branches of a tree

查看:45
本文介绍了查询选择树的所有分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的类别表

id | title | parent_id
---|-------|------------
1  | cat1  |  null
2  | cat2  |  null
3  | cat3  |  1
4  | cat4  |  1
5  | cat5  |  3
6  | cat6  |  5
7  | cat7  |  6
8  | cat8  |  7

我想知道我怎样才能拥有主要类别及其分支和一列,该列为我提供每棵树的分支计数例如,对于主类别 cat1 是这样的:

I want to know how can I have the main categories with their branches and a column that gives me the count branches of each tree for example something like this for the main category cat1 :

cat1 => cat3 => cat5 => cat6 => cat7 => cat8

谢谢

推荐答案

以数组的形式从数据库中获取所有条目.

get all entries from the database in the form of an array.

select * from categories;

$name = [];
$parent = [];
$children = [];

foreach($categories as $category){
    $name[$category['id']] = $category['name'];
    
    $parent[$category['id']] = $category['parent_id'];

    if(isset($category['parent_id'])){
       $children[$category['parent_id']][] = $category['id'];
    }
}

现在 $children[$category_id] 数组中的每个类别都有子项.

Now you have children for every category in the $children[$category_id] array.

和每个孩子的父母

打印从任何孩子到根的遍历.

To print the traversal from any child to the root.

$id = `any id`;

while(isset($id)){
   echo $name[$id] . " => ";
   $id = isset(parent[$id] ? parent[$id] : null); 
}

获取任意节点的子节点数.

To get the count of children of any node.

echo sizeof($children[$category_id]);

现在,当涉及到从父节点到子节点的遍历时,可以有很多选择,因为一个节点可以有多个子节点.

Now, when it comes to traversal from parent to a child, there can be many options as one node can have more than one child.

我正在编写选择随机子节点并进行下一级遍历的代码.

I'm writing the code that picks random child and goes for the traversal to the next level.

$id = `any id`;

while(isset($id)){
   echo $name[$id] . " => ";
   if(isset($children[$id])){
     $idx = array_rand($children[$id], 1);
     $id = $children[$idx];
   }
   else{
      // This means you've reached the leaf node.
      $id = null;
   }
}

这篇关于查询选择树的所有分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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