/**
* @param $items
* @param int $pid 父级ID
* @param bool $children
* @param string $title
* @return array
*/
function getTree( $items , $pid = 0, $children = true, $title = 'children')
{
// 每次都声明一个新数组用来放子元素
$tree = [];
foreach( $items as $item ){
// 匹配子记录
if( $item['pid'] == $pid){
// 递归获取子记录
$item[$title] = getTree( $items , $item['id'], $children, $title);
if( $item[$title] == null && $children){
// 如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)
unset($item[$title]);
}
// 将记录存入新数组
$tree[] = $item;
}
}
// 返回新数组
return $tree;
}
(做的笔记,只是自己看的)