无限极分类封装方法:
if(! function_exists('treeCategory'))
{
/**
* @param array $datas 原数组
* @param int $parent 默认父级id=0
* @param string $key 条件子级字段
* @param string $leaf 条件父级字段
* @param string|null $sortColumn 表中需要排序的字段 默认空
* @param int $order SORT_ASC默认升序 SORT_DESC降序
* @param int $maxDeep 设置最大层级
* @param array $nullLeaf
* @param int $deep 默认层级0
* @return array
*/
function treeCategory( array $datas, $parent = 0, string $key = 'id', string $leaf = "parentId", string $sortColumn = null, $order = SORT_ASC, $maxDeep = 99, array &$nullLeaf = [], int $deep = 0 )
{
$tree = [];
$leafs = array_column($datas, $leaf);
if( in_array($parent, $leafs) ) {
$deep++;
if( $maxDeep !== -1 && $deep <= $maxDeep ) {
if( !isset($nullLeaf[$deep]) )
$nullLeaf[$deep] = [
'deep' => $deep,
'nullLeaf' => [],
];
foreach ( $datas as $data ) {
if( $data[$leaf] != $parent )
continue;
$tree[$data[$key]] = $data;
$tree[$data[$key]]['deep'] = $deep;
$tree[$data[$key]]['children'] = toTree( $datas, $data[$key], $key, $leaf, $sortColumn, $order, $maxDeep, $nullLeaf, $deep );
if( count($tree[$data[$key]]['children']) == 0 )
$nullLeaf[$deep]['nullLeaf'][] = $data[$key];
}
if( !empty( $sortColumn ) )
if( count($tree) > 0 )
array_multisort(array_column($tree, $sortColumn), $order, $tree);
}
}
return $tree;
}
}
使用: $tree = treeCategory($goodsTypes, 0, 'id', 'parentId', 'sort', SORT_ASC, 3);
返回数据以权限列表示例: