直接上代码 + 示例
<?php
/**
* php递归生成树形结构 - 无限分类 - 构建树形结构 - 省市区三级联动
*
* @param array $lists 一维数组,包括不同级别的各行数据
* @param int $parentId 目标节点的父类ID (可以是顶级分类的父ID,也可以是任意节点的父ID)
* @param string $keyParentId 数组下标 - 父类ID
* @param string $keySonId 数组下标 - 父类ID
* @param string $keyChildren 数组新增下标 - 子节点下标
*
* @author Rudon
* @link https://rudon.blog.csdn.net/
*/
function getTree($lists, $parentId = 0, $keyParentId = 'parent_id', $keySonId = 'id', $keyChildren = 'children') {
$tree = [];
foreach($lists as $k => $v)
{
if(array_key_exists($keySonId, $v) && array_key_exists($keyParentId, $v) && $v[$keyParentId] == $parentId) {
$v[$keyChildren] = getTree($lists, $v[$keySonId], $keyParentId, $keySonId, $keyChildren);
$tree[] = $v;
}
}
return $tree;
}
// 示例
$rows = array(
array('id' => 1, 'parent_id' => 0, 'name' => '河北省'),
array('id' => 2, 'parent_id' => 0, 'name' => '北京市'),
array('id' => 3, 'parent_id' => 1, 'name' => '邯郸市'),
array('id' => 4, 'parent_id' => 2, 'name' => '朝阳区'),
array('id' => 5, 'parent_id' => 2, 'name' => '通州区'),
array('id' => 6, 'parent_id' => 4, 'name' => '望京'),
array('id' => 7, 'parent_id' => 4, 'name' => '酒仙桥'),
array('id' => 8, 'parent_id' => 3, 'name' => '永年区'),
array('id' => 9, 'parent_id' => 1, 'name' => '武安市'),
array('id' => 10, 'parent_id' => 8, 'name' => '永年区镇'),
array('id' => 11, 'parent_id' => 0, 'name' => '上海市')
);
// 获取所有省市区关系
$tree = getTree($rows, 0);
echo "<pre>";
print_r($tree);
echo "</pre>";
// 获取北京市(ID=2)的各下级
// $tree = getTree($rows, 2);
// 结果
/**
*
Array
(
[0] => Array
(
[id] => 1
[parent_id] => 0
[name] => 河北省
[children] => Array
(
[0] => Array
(
[id] => 3
[parent_id] => 1
[name] => 邯郸市
[children] => Array
(
[0] => Array
(
[id] => 8
[parent_id] => 3
[name] => 永年区
[children] => Array
(
[0] => Array
(
[id] => 10
[parent_id] => 8
[name] => 永年区镇
[children] => Array
(
)
)
)
)
)
)
[1] => Array
(
[id] => 9
[parent_id] => 1
[name] => 武安市
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 2
[parent_id] => 0
[name] => 北京市
[children] => Array
(
[0] => Array
(
[id] => 4
[parent_id] => 2
[name] => 朝阳区
[children] => Array
(
[0] => Array
(
[id] => 6
[parent_id] => 4
[name] => 望京
[children] => Array
(
)
)
[1] => Array
(
[id] => 7
[parent_id] => 4
[name] => 酒仙桥
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 5
[parent_id] => 2
[name] => 通州区
[children] => Array
(
)
)
)
)
[2] => Array
(
[id] => 11
[parent_id] => 0
[name] => 上海市
[children] => Array
(
)
)
)
*
*/