首頁  >  文章  >  後端開發  >  php如何高效找出所有下級

php如何高效找出所有下級

尚
原創
2019-10-29 15:01:354011瀏覽

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