美文网首页
php实现无限极分类

php实现无限极分类

作者: warcello | 来源:发表于2018-05-15 11:24 被阅读40次

    一、两种实现php无限极分类

    设置原始数据

    public function index()
        {
            $items = array(
                1 => array('id' => 1, 'pid' => 0, 'name' => '江西省'),
                2 => array('id' => 2, 'pid' => 0, 'name' => '黑龙江省'),
                3 => array('id' => 3, 'pid' => 1, 'name' => '南昌市'),
                4 => array('id' => 4, 'pid' => 2, 'name' => '哈尔滨市'),
                5 => array('id' => 5, 'pid' => 2, 'name' => '鸡西市'),
                6 => array('id' => 6, 'pid' => 4, 'name' => '香坊区'),
                7 => array('id' => 7, 'pid' => 4, 'name' => '南岗区'),
                8 => array('id' => 8, 'pid' => 6, 'name' => '和兴路'),
                9 => array('id' => 9, 'pid' => 7, 'name' => '西大直街'),
                10 => array('id' => 10, 'pid' => 8, 'name' => '东北林业大学'),
                11 => array('id' => 11, 'pid' => 9, 'name' => '哈尔滨工业大学'),
                12 => array('id' => 12, 'pid' => 8, 'name' => '哈尔滨师范大学'),
                13 => array('id' => 13, 'pid' => 1, 'name' => '赣州市'),
                14 => array('id' => 14, 'pid' => 13, 'name' => '赣县'),
                15 => array('id' => 15, 'pid' => 13, 'name' => '于都县'),
                16 => array('id' => 16, 'pid' => 14, 'name' => '茅店镇'),
                17 => array('id' => 17, 'pid' => 14, 'name' => '大田乡'),
                18 => array('id' => 18, 'pid' => 16, 'name' => '义源村'),
                19 => array('id' => 19, 'pid' => 16, 'name' => '上坝村'),
            );
    
            print_r($this->getTree1($items));
            print_r($this->getTree1($items));
        }
    

    1. 使用php递归实现php无限极分类

    通过foreach循环实现无限极分类这种方式比较好理解

    public function getTree1($items,$pid=0)
        {
            $array = [];
            foreach ($items as $key => $item) {
                if( $item['pid'] == $pid )
                {
                    $array[$key] = $val;
                    $array[$key]['son'] = $this->getTree1( $items, $item['pid']);
                }
            }
            return $array;
        }
    

    2.通过引用实现php无限极分类

    /**
         * 递归加引用实现无限极分类
         * @param $items
         * @return array
         */
        public function getTree2($items)
        {
            $array = [];
            foreach ($items as $item)
            {
                if(isset($items[$item['pid']]))
                {
                    $items[$item['pid']]['son'][] = &$items[$item['id']];
                }else {
                    $array[] = &$items[$item['id']];
                }
            }
            return $array;
        }
    

    相关文章

      网友评论

          本文标题:php实现无限极分类

          本文链接:https://www.haomeiwen.com/subject/nveedftx.html