Home > Backend Development > PHP Problem > How to efficiently find all subordinates in php

How to efficiently find all subordinates in php

Release: 2023-02-27 22:42:01
Original
4065 people have browsed it

How to efficiently find all subordinates in php

PHP efficiently removes all subordinates:

Recursively removes all subordinates:

<?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));
 
 
 
?>
Copy after login

Recommended: php server

The above is the detailed content of How to efficiently find all subordinates in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template