php递归生成树形结构 - 无限分类 - 构建树形结构 - 省市区三级联动

直接上代码 + 示例

 $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 "
";
    print_r($tree);
    echo "
"; // 获取北京市(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 ( ) ) ) * */

php递归生成树形结构 - 无限分类 - 构建树形结构 - 省市区三级联动_第1张图片

你可能感兴趣的:(开发,PHP,php,递归,树形结构,java)