數(shù)據(jù)庫文件xd_item:
id pid item lead ...
1 0 標(biāo)題名稱一
2 0 標(biāo)題名稱二
3 1 中標(biāo)題名稱1-1
4 1 中標(biāo)題名稱1-2
5 2 中標(biāo)題名稱2-1
6 2 中標(biāo)題名稱2-2
8 3 小標(biāo)題名稱1-1-1
9 6 小標(biāo)題名稱2-2-1
10 6 小標(biāo)題名稱2-2-2
11 2 中標(biāo)題名稱2-3
---------------------
輸出效果:
序號 項目名稱
1 標(biāo)題名稱一
1.1 中標(biāo)題名稱1-1
1.1.1 小標(biāo)題名稱1-1-1
1.2 中標(biāo)題名稱1-2
2 標(biāo)題名稱二
2.1 中標(biāo)題名稱2-1
2.2 中標(biāo)題名稱2-2
2.2.1 小標(biāo)題名稱2-2-1
2.2.2 小標(biāo)題名稱2-2-2
2.3 中標(biāo)題名稱2-3
============================
要在PHP實現(xiàn)這個輸出效果,要怎么實現(xiàn)呢?
First query those whose pid is 0, traverse those whose pid is 0, query those whose pid is the id of these items, and then output in a loop
If it is Oracle, you can use level() and sys_connect_by_path() functions to implement it.
If you do not use functions, you can build a view to implement it.
This is a reference to my method, which uses recursion to traverse. As long as it deals with data structures, there are methods, it just depends on the efficiency
static public function toLevel($cate, $delimiter = '|——', $parent_id = 0, $level = 0) {
$arr = array();
foreach ($cate as $v) {
if ($v['parent_id'] == $parent_id) {
$v['type'] = $level + 1;
$v['delimiter'] = str_repeat($delimiter, $level);
$arr[] = $v;
$arr = array_merge($arr, self::toLevel($cate, $delimiter, $v['cate_id'], $v['type']));
}
}
return $arr;
}
Query the data using function calls. The first one perfectly supports your needs, and the second one is recursive storage of data
$arr = [
0=>['id'=>1,'pid'=>0,'title'=>'標(biāo)題名稱一'],
1=>['id'=>2,'pid'=>0,'title'=>'標(biāo)題名稱一'],
2=>['id'=>3,'pid'=>1,'title'=>'標(biāo)題名稱一'],
3=>['id'=>4,'pid'=>1,'title'=>'標(biāo)題名稱一'],
4=>['id'=>5,'pid'=>2,'title'=>'標(biāo)題名稱一'],
5=>['id'=>6,'pid'=>2,'title'=>'標(biāo)題名稱一'],
6=>['id'=>7,'pid'=>3,'title'=>'標(biāo)題名稱一'],
7=>['id'=>8,'pid'=>3,'title'=>'標(biāo)題名稱一'],
8=>['id'=>9,'pid'=>6,'title'=>'標(biāo)題名稱一'],
9=>['id'=>10,'pid'=>6,'title'=>'標(biāo)題名稱一'],
10=>['id'=>11,'pid'=>2,'title'=>'標(biāo)題名稱一'],
];
$result = foreachd($arr,0);var_dump($result);
function foreachd($arr,$pid,$showpage = '') {
$setpage = 1;
$result = array();
foreach($arr as $key=>$val) {
if($val['pid'] == $pid) {
$setshowpage = $showpage == '' ? $setpage : $showpage.'.'.$setpage;
$arr[$key]['page'] = $setshowpage;
$setpage++;
$setarray = ['page'=>$setshowpage,'title'=>$val['title']];
$result[] = $setarray;
$result = array_merge($result,foreachd($arr,$val['id'],$setshowpage));
}
}
return $result;
}
/*function foreachd($arr,$pid) {
$return = array();
foreach($arr as $val) {
if($val['pid'] == $pid) {
$return[$val['id']]['title'] = $val['title'];
$childrendata = foreachd($arr,$val['id']);
if($childrendata) {
$return[$val['id']]['children'] = $childrendata;
}
}
}
return $return;
}*/