首页  >  文章  >  后端开发  >  php如何高效找出所有下级

php如何高效找出所有下级

尚
原创
2019-10-29 15:01:354009浏览

php如何高效找出所有下级

PHP高效的取出所有下级:

递归取出所有下级:

<?php
 
$data = [
	[
		&#39;uid&#39; => 1,
		&#39;username&#39; => &#39;155&#39;,
		&#39;parent_username&#39; => &#39;0&#39;
	],
	[
		&#39;uid&#39; => 2,
		&#39;username&#39; => &#39;186&#39;,
		&#39;parent_username&#39; => &#39;155&#39;
	],
	[
		&#39;uid&#39; => 3,
		&#39;username&#39; => &#39;189&#39;,
		&#39;parent_username&#39; => &#39;186&#39;
	],
	[
		&#39;uid&#39; => 4,
		&#39;username&#39; => &#39;188&#39;,
		&#39;parent_username&#39; => &#39;155&#39;
	],
	[
		&#39;uid&#39; => 5,
		&#39;username&#39; => &#39;187&#39;,
		&#39;parent_username&#39; => &#39;188&#39;
	],
	[
		&#39;uid&#39; => 6,
		&#39;username&#39; => &#39;1898&#39;,
		&#39;parent_username&#39; => &#39;146&#39;
	],
];
 
/**
 * 获取所有下级
 * [getTree description]
 * @param  [type] $data            [description]
 * @param  string $parent_username [description]
 * @return [type]                  [description]
 */
//有层次,返回所有下级数据
function getTree($data, $parent_username = &#39;0&#39;)
{
    $arr = [];
	foreach($data as $key => $val){
		if($val[&#39;parent_username&#39;] == $parent_username){
			$val[&#39;children&#39;] = getTree($data, $val[&#39;username&#39;]);
			$arr[] = $val;
		}
	}
	return $arr;
}
 
//无层次,仅返回id
function getTree($data, $parent_username = &#39;0&#39;, $is_first_time = true)
{
    static $arr = [];
    if ($is_first_time) {
        $arr = [];
    }
    foreach ($data as $key => $val) {
        if ($val[&#39;parent_username&#39;] == $parent_username) {
            $arr[]           = $val[&#39;uid&#39;];
            getTree($data, $val[&#39;username&#39;], false);
        }
    }
    return $arr;
}
 
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r(getTree($data));
 
 
 
?>

推荐:php服务器

以上是php如何高效找出所有下级的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn