http://blog.csdn.net/qishouzhang/article/details/47204359
<?php
/**
* Created by PhpStorm.
* User: qishou
* Date: 15-8-2
* Time: 上午12:00
*/
//准备数组,代替从数据库中检索出的数据(共有三个必须字段id,name,pid)
header("content-type:text/html;charset=utf-8");
$categories = array(
array('id'=>1,'name'=>'电脑','pid'=>0),
array('id'=>2,'name'=>'手机','pid'=>0),
array('id'=>3,'name'=>'笔记本','pid'=>1),
array('id'=>4,'name'=>'台式机','pid'=>1),
array('id'=>5,'name'=>'智能机','pid'=>2),
array('id'=>6,'name'=>'功能机','pid'=>2),
array('id'=>7,'name'=>'超级本','pid'=>3),
array('id'=>8,'name'=>'游戏本','pid'=>3),
);
/*======================非递归实现========================*/
$tree = array();
//第一步,将分类id作为数组key,并创建children单元
foreach($categories as $category){
$tree[$category['id']] = $category;
$tree[$category['id']]['children'] = array();
}
//第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。
foreach($tree as $key=>$item){
if($item['pid'] != 0){
$tree[$item['pid']]['children'][] = &$tree[$key];//注意:此处必须传引用否则结果不对
if($tree[$key]['children'] == null){
unset($tree[$key]['children']); //如果children为空,则删除该children元素(可选)
}
}
}
第三步,删除无用的非根节点数据
foreach($tree as $key=>$category){
if($category['pid'] != 0){
unset($tree[$key]);
}
}
print_r($tree);
/*======================递归实现========================*/
$tree = $categories;
function get_attr($a,$pid){
$tree = array(); //每次都声明一个新数组用来放子元素
foreach($a as $v){
if($v['pid'] == $pid){ //匹配子记录
$v['children'] = get_attr($a,$v['id']); //递归获取子记录
if($v['children'] == null){
unset($v['children']); //如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)
}
$tree[] = $v; //将记录存入新数组
}
}
return $tree; //返回新数组
}
echo "<br/><br/><br/>";
print_r(get_attr($tree,0)); //传pid值 得到下级下下级的所有层级
得到某一节点下 所有子级 孙级id
$ids = [];
$tree = $this->get_attr($tree,1,$ids);
function get_attr2($a,$pid,&$ids){
$tree = array(); //每次都声明一个新数组用来放子元素
foreach($a as $v){
if($v['org_parent_id'] == $pid){ //匹配子记录
array_push($ids,$v['id']);
$v['children'] = $this->get_attr($a,$v['id'],$ids); //递归获取子记录
//var_dump($v['id']);
if($v['children'] == null){
unset($v['children']); //如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)
}
$tree[] = $v; //将记录存入新数组
}
}
return $ids; //返回新数组
}
得到某一id下的所有子层级id
$tree = M()->query("select * from company_org where company_id = '$company_id'");
$tree = $this->getMenuTree($tree,$department_id,$org_level);
//如果有子级则 子级加本级数据
if($tree){
$tree = i_array_column($tree,'id');
array_push($tree,$department_id);
$tree = implode(",",$tree);
}else{ //如果没有子级 则只是本级数据
$tree = $department_id;
}
$sql = "select * from employee where department_id in ($tree)";
$employee_list = M()->query($sql);
function getMenuTree($arrCat, $parent_id = 0, $level = 0)
{
static $arrTree = array(); //使用static代替global
if( empty($arrCat)) return FALSE;
$level++;
foreach($arrCat as $key => $value)
{
if($value['org_parent_id' ] == $parent_id)
{
$value[ 'org_level'] = $level;
$arrTree[] = $value;
unset($arrCat[$key]); //注销当前节点数据,减少已无用的遍历
$this->getMenuTree($arrCat, $value[ 'id'], $level);
}
}
return $arrTree;
}