PHP不使用递归的无限级分类简单实例

5年以前  |  阅读数:955 次  |  编程语言:PHP 

不用递归实现无限级分类,简单测试了下性能比递归稍好一点点点,但写得太复杂了,还是递归简单方便点

代码:


    <?php
    $list = array(
      array('id'=>1, 'pid'=>0, 'deep'=>0, 'name'=>'test1'),
      array('id'=>2, 'pid'=>1, 'deep'=>1, 'name'=>'test2'),
      array('id'=>3, 'pid'=>0, 'deep'=>0, 'name'=>'test3'),
      array('id'=>4, 'pid'=>2, 'deep'=>2, 'name'=>'test4'),
      array('id'=>5, 'pid'=>2, 'deep'=>2, 'name'=>'test5'),
      array('id'=>6, 'pid'=>0, 'deep'=>0, 'name'=>'test6'),
      array('id'=>7, 'pid'=>2, 'deep'=>2, 'name'=>'test7'),
      array('id'=>8, 'pid'=>5, 'deep'=>3, 'name'=>'test8'),
      array('id'=>9, 'pid'=>3, 'deep'=>2, 'name'=>'test9'),
    );
    function resolve($list) {
      $newList = $manages = $deeps = $inDeeps = array();
      foreach ($list as $row) {
        $newList[$row['id']] = $row;
      }
      $list = null;
      foreach ($newList as $row) {
        if (! isset($manages[$row['pid']]) || ! isset($manages[$row['pid']]['children'][$row['id']])) {
          if ($row['pid'] > 0 && ! isset($manages[$row['pid']]['children'])) $manages[$row['pid']] = $newList[$row['pid']];
          $manages[$row['pid']]['children'][$row['id']] = $row;
        }
        if (! isset($inDeeps[$row['deep']]) || ! in_array($row['id'], $inDeeps[$row['deep']])) {
          $inDeeps[$row['deep']][] = array($row['pid'], $row['id']);
        }
      }
      krsort($inDeeps);
      array_shift($inDeeps);
      foreach ($inDeeps as $deep => $ids) {
        foreach ($ids as $m) {
          // 存在子栏目的进行转移
          if (isset($manages[$m[1]])) {
            $manages[$m[0]]['children'][$m[1]] = $manages[$m[1]];
            $manages[$m[1]] = null;
            unset($manages[$m[1]]);
          }
        }
      }
      return $manages[0]['children'];
    }

递归实现


    function resolve2(& $list, $pid = 0) {
      $manages = array();
      foreach ($list as $row) {
        if ($row['pid'] == $pid) {
          $manages[$row['id']] = $row;
          $children = resolve2($list, $row['id']);
          $children && $manages[$row['id']]['children'] = $children;
        }
      }
      return $manages;
    }

以上这篇PHP不使用递归的无限级分类简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
获取IMSI
将二进制数据转为16进制以便显示
获取IMEI
文件下载
贪吃蛇
双位运算符
PHP自定义函数获取搜索引擎来源关键字的方法
Java生成UUID
发送邮件
年的日历图
提取后缀名
在Zeus Web Server中安装PHP语言支持
让你成为最历害的git提交人
Yii2汉字转拼音类的实例代码
再谈PHP中单双引号的区别详解
指定应用ID以获取对应的应用名称
Python 2与Python 3版本和编码的对比
php封装的page分页类完整实例