无限极分类简单实例

希望大家理解其意,学其意而非形。递归 和parent_id。(这里面包含了php数组的新写法 $a=[ ];)

<?php

/**
 * Created by PhpStorm.
 * User: kok
 * Date: 3/19/16
 * Time: 12:50 PM
 */
class wuxianji
{
    public function __construct($a)
    {
        $this->cats = $a;
    }

    public function getTree($p = 0)
    {
        $tree = array();
        foreach ($this->cats as $k=> $v) {
            if ($v['parent_id'] == $p) {
                $tree[] = $v;
                $tree = array_merge($tree, $this->getTree($v['cat_id']));
            }
        }
        return $tree;
    }


}
$b=[
            ['cat_id'=>1,'name'=>'手机','parent_id'=>0],
            ['cat_id'=>2,'name'=>'安卓手机','parent_id'=>1],
            ['cat_id'=>3,'name'=>'苹果手机','parent_id'=>1],
            ['cat_id'=>4,'name'=>'电脑','parent_id'=>0],
            ['cat_id'=>5,'name'=>'魅族手机','parent_id'=>2],
            ['cat_id'=>6,'name'=>'iphone','parent_id'=>3],   
            ['cat_id'=>7,'name'=>'平板','parent_id'=>6],
            ['cat_id'=>8,'name'=>'笔记本','parent_id'=>7],
            ['cat_id'=>9,'name'=>'台式','parent_id'=>7]
    ];
$a = new wuxianji($b);
print_r($a->getTree());


2016-05-14 23:54:06
nickname
content