php
复制代码
public function getCategoryTree()
{
// 模拟的数据数组
$array = [
['id' => 1, 'pid' => 0, 'name' => '河北省'],
['id' => 2, 'pid' => 0, 'name' => '北京市'],
['id' => 3, 'pid' => 1, 'name' => '邯郸市'],
['id' => 4, 'pid' => 2, 'name' => '朝阳区'],
['id' => 5, 'pid' => 2, 'name' => '通州区'],
['id' => 6, 'pid' => 4, 'name' => '望京'],
['id' => 7, 'pid' => 4, 'name' => '酒仙桥'],
['id' => 8, 'pid' => 3, 'name' => '永年区'],
['id' => 9, 'pid' => 1, 'name' => '武安市'],
];
// 调用递归函数生成无限极分类数组
$categories = $this->generateTree($array);
// 直接输出JSON格式的分类数组
return json($categories);
}
/**
* 递归生成无限极分类数组
* @param array $data 数据源
* @param int $pid 父级ID,默认为0
* @return array
* 思路: *
* 第一次调用$data数组,得到pid=0的根节点,为其添加children子节点,将找到的根节点赋值给$tree,然后跳出循环
* 第二次调用$data,得到pid等于根节点的子节点
*/
private function generateTree($data, $pid = 0)
{
$tree = [];
foreach ($data as $value) {
if ($value['pid'] == $pid) {
$value['children'] = $this->generateTree($data, $value['id']);
$tree[] = $value;
}
}
return $tree;
}