PHP查找数据库中自己的所有子集,包括子集的子集,
public function getDataFind($table,$where=[]){
$data = Db::name($table)->where($where)->field('id,pid,username')->find();
return $data;
}
public function getParent($uid){//当前用户id
static $arr = [];
$member = DB::name('user')->where('pid',$uid)->field('id,pid,username')->select();
foreach ($member as $member){
if ($member['id'] > 0){
$parent = $this->getDataFind('user',array('id'=>$member['id']));
$arr[]=$parent['id'];
$this->getParent($parent['id']);
}
}
return $arr;
}
?结果
?
?
?如果想以多维数组的形式展示出来的话
/**
* 获取分类函数
*/
function getTree($list,$type='1',$pid){
if(empty($pid)){
$this->error('失败',0);
}
$return = [];
foreach ($list as $k => $v) {
//这里要根据数组中实际的键对应起来
if($v['pid']==$pid){
$return[$k] = $v;
//这里要根据数组中实际的键对应起来
$return[$k]['pid'] = $v['pid'];
$return[$k]['child'] = array_values($this->getTree($list,'1',$v['id'])) ;
}
// unset($list[$k]);
}
return $return;
}
?结果
"data": {
"id": 8,
"child": [
{
"id": 6,
"pid": 8,
"child": [
{
"id": 4,
"pid": 6,
"child": []
},
{
"id": 5,
"pid": 6,
"child": []
}
]
},
{
"id": 7,
"pid": 8,
"child": [
{
"id": 23,
"pid": 7,
"child": []
},
{
"id": 27,
"pid": 7,
"child": []
}
]
}
]
}
?
查询用的tp5
注意一点 :如果需要走循环任务的话 static $arr = []; 一定要在程序外面定义,否则会出现数据累计的情况。
|