50

一段生成无限级别分类的代码思考

 5 years ago
source link: http://www.10tiao.com/html/728/201807/2653356090/1.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Talk is cheap,show me the code.

笔者也不爽约,先丢上代码:

  1. <?php

  2. $areas = array(

  3.  1 => array('id' => 1, 'pid' => 0, 'name' => '江西省'),

  4.  2 => array('id' => 2, 'pid' => 0, 'name' => '黑龙江省'),

  5.  3 => array('id' => 3, 'pid' => 1, 'name' => '南昌市'),

  6.  4 => array('id' => 4, 'pid' => 2, 'name' => '哈尔滨市'),

  7.  5 => array('id' => 5, 'pid' => 2, 'name' => '鸡西市'),

  8.  6 => array('id' => 6, 'pid' => 4, 'name' => '香坊区'),

  9.  7 => array('id' => 7, 'pid' => 4, 'name' => '南岗区'),

  10.  8 => array('id' => 8, 'pid' => 6, 'name' => '和兴路'),

  11.  9 => array('id' => 9, 'pid' => 7, 'name' => '西大直街'),

  12.  10 => array('id' => 10, 'pid' => 8, 'name' => '东北林业大学'),

  13.  11 => array('id' => 11, 'pid' => 9, 'name' => '哈尔滨工业大学'),

  14.  12 => array('id' => 12, 'pid' => 8, 'name' => '哈尔滨师范大学'),

  15.  13 => array('id' => 13, 'pid' => 1, 'name' => '赣州市'),

  16.  14 => array('id' => 14, 'pid' => 13, 'name' => '赣县'),

  17.  15 => array('id' => 15, 'pid' => 13, 'name' => '于都县'),

  18.  16 => array('id' => 16, 'pid' => 14, 'name' => '茅店镇'),

  19.  17 => array('id' => 17, 'pid' => 14, 'name' => '大田乡'),

  20.  18 => array('id' => 18, 'pid' => 16, 'name' => '义源村'),

  21.  19 => array('id' => 19, 'pid' => 16, 'name' => '上坝村'),

  22. );

  23. function makeTree($areas)

  24. {

  25.  $areaTree = [];

  26.  foreach ($areas as $id=>$area){

  27.  if(isset($areas[$area["pid"]])){

  28.  $areas[$area["pid"]]["children"][] = &$areas[$id];

  29.  } else {

  30.  $areaTree[] = &$areas[$area["id"]];

  31.  }

  32.  }

  33.  return $areaTree;

  34. }

  35. echo json_encode(makeTree($areas));

结果如下:

上图未展示全部内容。


我们可以看到,原本比较复杂无限极别的分类树状结构的类目被轻易实现了,我想很多小伙伴还不知道是原理是几何,下面我们对上面的代码片段进行分析。

首先是我们的区域数据$areas,数组的键必须跟元素的id键对应值相等,pid表示父元素的对应的键,当元素pid等于0时则表示它本身是最顶层的元素,这个数据比较像省市县等多级分类的树状结构的数据,有些同学可能要问了,什么是树状结构,为了比较形象地说明这个结构我盗用下面这张图:


其次是,makeTree函数里面的算法用到了PHP的&引用符号,这里主要在于利用引用可以将对元素后续的修改操作影响到之前已有的元素,这也是引用的魔力所在,这里的理解可能有点绕,需要同学们自己好好理解一下PHP引用的原理和用法才行,官方文档:http://www.php.net/manual/zh/language.references.pass.php。

另外,需要注意的是当我们想要分类按照一定的顺序排列的时候,最好能够加上一个sort字段,根据sort的值降序排列分类项即可,若sort的值是一样的,则按照元素的id降序,这样就能保持一致的分类树输出了。


拓展一下,我们借助zTree,就可以轻松实现我们需要的树状结构了,不过通过zTree这个js插件,我们甚至不需要在后端进行makeTree的预处理。




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK