CAT_ID cat_name pid Cat_pat
Category ID (self-increment) category name 0 (parent ID, if 0 is the root category, the self-increment ID) path
May I ask you the great God, can give the best method, directly with the category ID 1 to query out all the following sub-categories
The data table is as follows:
ID cat_name PID Cat_path
1 Mobile 0,
2 Smartphones 1, 1,
3 Samsung 2, 1, 2,
4 Samsung S Series 3,
5 Samsung M Series 3,.
Reply content:
CAT_ID cat_name pid Cat_pat
Category ID (self-increment) category name 0 (parent ID, if 0 is the root category, the self-increment ID) path
May I ask you the great God, can give the best method, directly with the category ID 1 to query out all the following sub-categories
The data table is as follows:
ID cat_name PID Cat_path
1 Mobile 0,
2 Smartphones 1, 1,
3 Samsung 2, 1, 2,
4 Samsung S Series 3,
5 Samsung M Series 3,.
No one answered, there was a job that had been done a while ago, to give you the algorithm.
The idea is as follows: use a stack to temporarily save the unhandled root node and all its child nodes, constantly take a node input from the stack, and put its immediate child nodes, pressing onto the stack until the stack is empty and the algorithm ends.
I have rewritten the detailed comments for you, to understand that should not be a problem!
$waitList = array(); //等待堆栈(数组用做堆栈),未处理的id array_push($waitList, $_GET["cid"]); //我这是点中某个节点(cid),列出所有子类中的数据 $rsList = array(); //结果队列 while (count($waitList) > 0) { //等待堆栈中还有节点,继续处理 $tmp = array_pop($waitList); //取出一个节点 array_push($rsList, $tmp); //输出这个节点 $dc = M("DocCategory"); //从数据表中找出这个节点的所有子节点 $dcon['pid'] = $tmp; $dcs = $dc->where($dcon)->field('id')->select(); foreach ($dcs as $value) { //将所有子节点压入等待堆栈 array_push($waitList, $value['id']); } } $con['category'] = array('in', $rsList); //生成查询条件,等待队列中已经包含了所有的子节点