php 引用地址符&实现无限极分类

算法利用了循环迭代,将线性结构按照父子关系以树形结构输出,算法的关键在于使用了&引用.

优点:速度快,效率高.

缺点:数组的key值必须与id值相同,不便于取出数据(使用递归获取数据), 数据必须一次性取出

$tree = []; // 格式化好的数组
$regionArr = array(
            array('id' => 1, 'pid' => 0, 'name' => '河北省'),
            array('id' => 2, 'pid' => 0, 'name' => '北京市'),
            array('id' => 3, 'pid' => 1, 'name' => '邯郸市'),
            array('id' => 4, 'pid' => 2, 'name' => '朝阳区'),
            array('id' => 5, 'pid' => 2, 'name' => '通州区'),
            array('id' => 6, 'pid' => 4, 'name' => '望京'),
            array('id' => 7, 'pid' => 4, 'name' => '酒仙桥'),
            array('id' => 8, 'pid' => 3, 'name' => '永年区'),
            array('id' => 9, 'pid' => 1, 'name' => '武安市'),
);

$regionIdTemp = $regionArr ? array_column($regionArr, null, 'id') : [];
foreach ($regionArr as $item) {
    $id = $item['id'];
    $item['pid'] != 0 ? $regionIdTemp[$item['pid']]['children'][] = &$regionIdTemp[$id] : $tree[] = &$regionIdTemp[$id];
}

 halt($tree);

输出结果如下:

array(2) {
  [0] => &array(4) {
    ["id"] => int(1)
    ["pid"] => int(0)
    ["name"] => string(9) "河北省"
    ["children"] => array(2) {
      [0] => &array(4) {
        ["id"] => int(3)
        ["pid"] => int(1)
        ["name"] => string(9) "邯郸市"
        ["children"] => array(1) {
          [0] => &array(3) {
            ["id"] => int(8)
            ["pid"] => int(3)
            ["name"] => string(9) "永年区"
          }
        }
      }
      [1] => &array(3) {
        ["id"] => int(9)
        ["pid"] => int(1)
        ["name"] => string(9) "武安市"
      }
    }
  }
  [1] => &array(4) {
    ["id"] => int(2)
    ["pid"] => int(0)
    ["name"] => string(9) "北京市"
    ["children"] => array(2) {
      [0] => &array(4) {
        ["id"] => int(4)
        ["pid"] => int(2)
        ["name"] => string(9) "朝阳区"
        ["children"] => array(2) {
          [0] => &array(3) {
            ["id"] => int(6)
            ["pid"] => int(4)
            ["name"] => string(6) "望京"
          }
          [1] => &array(3) {
            ["id"] => int(7)
            ["pid"] => int(4)
            ["name"] => string(9) "酒仙桥"
          }
        }
      }
      [1] => &array(3) {
        ["id"] => int(5)
        ["pid"] => int(2)
        ["name"] => string(9) "通州区"
      }
    }
  }
}

学习笔记,如有侵权,请联系

你可能感兴趣的:(php,算法,php,数据库,算法)