php递归方法实现无限分类实例

数组代码如下:

  1. $items = array(
  2. array('id' => 1, 'pid' => 0, 'name' => '一级11' ),
  3. array('id' => 11, 'pid' => 0, 'name' => '一级12' ),
  4. array('id' => 2, 'pid' => 1, 'name' => '二级21' ),
  5. array('id' => 10, 'pid' => 11, 'name' => '二级22' ),
  6. array('id' => 3, 'pid' => 1, 'name' => '二级23' ),
  7. array('id' => 12, 'pid' => 11, 'name' => '二级24' ),
  8. array('id' => 13, 'pid' => 12, 'name' => '三级31' ),
  9. array('id' => 9, 'pid' => 1, 'name' => '二级25' ),
  10. );

函数代码如下:

  1. function formatTree($array, $pid = 0){
  2. $arr = array();
  3. $tem = array();
  4. foreach ($array as $v) {
  5. if ($v['pid'] == $pid) {
  6. $tem = formatTree($array, $v['id']);
  7. //判断是否存在子数组
  8. $tem && $v['son'] = $tem;
  9. $arr[] = $v;
  10. }
  11. }
  12. return $arr;
  13. }

其中,数组一定要包含id和pid用以指定数组值之间的层级关系.