php如何高效找出所有下級

2020-07-16 10:06:47

PHP高效的取出所有下級:

遞回取出所有下級:

<?php
 
$data = [
	[
		'uid' => 1,
		'username' => '155',
		'parent_username' => '0'
	],
	[
		'uid' => 2,
		'username' => '186',
		'parent_username' => '155'
	],
	[
		'uid' => 3,
		'username' => '189',
		'parent_username' => '186'
	],
	[
		'uid' => 4,
		'username' => '188',
		'parent_username' => '155'
	],
	[
		'uid' => 5,
		'username' => '187',
		'parent_username' => '188'
	],
	[
		'uid' => 6,
		'username' => '1898',
		'parent_username' => '146'
	],
];
 
/**
 * 獲取所有下級
 * [getTree description]
 * @param  [type] $data            [description]
 * @param  string $parent_username [description]
 * @return [type]                  [description]
 */
//有層次,返回所有下級資料
function getTree($data, $parent_username = '0')
{
    $arr = [];
	foreach($data as $key => $val){
		if($val['parent_username'] == $parent_username){
			$val['children'] = getTree($data, $val['username']);
			$arr[] = $val;
		}
	}
	return $arr;
}
 
//無層次,僅返回id
function getTree($data, $parent_username = '0', $is_first_time = true)
{
    static $arr = [];
    if ($is_first_time) {
        $arr = [];
    }
    foreach ($data as $key => $val) {
        if ($val['parent_username'] == $parent_username) {
            $arr[]           = $val['uid'];
            getTree($data, $val['username'], false);
        }
    }
    return $arr;
}
 
echo '<pre>';
print_r(getTree($data));
 
 
 
?>
以上就是php如何高效找出所有下級的詳細內容,更多請關注TW511.COM其它相關文章!