数组无限分类树模型序列化

<?php
$array = array(
    array('id'=>'1', 'name'=>'电子产品', 'parent_id'=>0),
    array('id'=>'2', 'name'=>'电脑', 'parent_id'=>1),
    array('id'=>'3', 'name'=>'笔记本', 'parent_id'=>2),
    array('id'=>'4', 'name'=>'台式电脑', 'parent_id'=>2),
    array('id'=>'5', 'name'=>'食物', 'parent_id'=>0),
    array('id'=>'6', 'name'=>'蔬菜', 'parent_id'=>5),
    array('id'=>'7', 'name'=>'白菜', 'parent_id'=>6),
    array('id'=>'8', 'name'=>'萝卜', 'parent_id'=>6),
);
class TreeCate 
{
    function __construct ($data) {
        $this->data = $data;
        $this->array = array();
    }

    public function getTree($parent_id = 0)
    {
        $tree = [];
        if (count($this->data) > 0) {
            foreach ($this->data as $key => $value) {
                //删除已经序列过的数组
                unset($this->data[$key]);
                if ($value['parent_id'] == $parent_id) {
                    $children = $this->getTree($value['id']);
                    if (!empty($children)) {
                        //生成子树模型,因为用了递归,从最后一层返回生成
                        $value['children'] = $children;
                    }
                    $tree[] = $value;
                }

            }
            return $tree;
        }
    }
}
$tree_cates = new TreeCate($array);
$cates = $tree_cates->getTree();
print_r($cates);

  这里只是生成了树模型数组,具体调用!

猜你喜欢

转载自www.cnblogs.com/firebirdweb/p/11548235.html