类别:PHP问题 / 日期:2019-12-02 / 浏览:86 / 评论:0

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服务器

以上就是php怎样高效找出一切下级的细致内容,更多请关注ki4网别的相干文章!

打赏

感谢您的赞助~

打开支付宝扫一扫,即可进行扫码打赏哦~

版权声明 : 本文未使用任何知识共享协议授权,您可以任何形式自由转载或使用。

 可能感兴趣的文章

评论区

发表评论 / 取消回复

必填

选填

选填

◎欢迎讨论,请在这里发表您的看法及观点。