函数get_tree_list:返回父子级树状结构
<?php
//返回 父子级树状结构
function get_tree_list($list)
{
//将每条数据中的id值作为其下标
$temp = [];
foreach ($list as $v) {
$v['son'] = [];
$temp[$v['id']] = $v;
}
//获取分类树
foreach ($temp as $k => $v) {
//第一的数据示例$temp[0]['son'][] = $temp[1];$temp[1]['son'][] = $temp[2];$temp[1]['son'][] = $temp[3];$temp[2]['son'][] = $temp['4']
$temp[$v['pid']]['son'][] = &$temp[$v['id']];
}
return isset($temp[0]['son']) ? $temp[0]['son'] : [];
}
//测试数据
$arr = [
['id'=>1,'name'=>'wyq1','sex'=>'男','pid'=>0],
['id'=>2,'name'=>'wyq2','sex'=>'男','pid'=>1],
['id'=>3,'name'=>'wyq3','sex'=>'男','pid'=>1],
['id'=>4,'name'=>'wyq4','sex'=>'男','pid'=>2],
];
$tree = get_tree_list($arr);
var_dump($tree);
返回示例
array(1) {
[0]=>
array(5) {
["id"]=>
int(1)
["name"]=>
string(4) "wyq1"
["sex"]=>
string(3) "男"
["pid"]=>
int(0)
["son"]=>
array(2) {
[0]=>
array(5) {
["id"]=>
int(2)
["name"]=>
string(4) "wyq2"
["sex"]=>
string(3) "男"
["pid"]=>
int(1)
["son"]=>
array(1) {
[0]=>
array(5) {
["id"]=>
int(4)
["name"]=>
string(4) "wyq4"
["sex"]=>
string(3) "男"
["pid"]=>
int(2)
["son"]=>
array(0) {
}
}
}
}
[1]=>
array(5) {
["id"]=>
int(3)
["name"]=>
string(4) "wyq3"
["sex"]=>
string(3) "男"
["pid"]=>
int(1)
["son"]=>
array(0) {
}
}
}
}
}