首頁 > 後端開發 > PHP問題 > php如何高效找出所有下級

php如何高效找出所有下級

發布: 2023-02-27 22:42:01
原創
4065 人瀏覽過

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中文網其他相關文章!

相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板