php实现无限级分类

Posted hea7r9o4

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php实现无限级分类相关的知识,希望对你有一定的参考价值。

//无限级分类
$list = array(
    array(\'id\' => 1, \'pid\' => 0, \'name\' => \'河北省\'),
    array(\'id\' => 2, \'pid\' => 0, \'name\' => \'北京市\'),
    array(\'id\' => 3, \'pid\' => 1, \'name\' => \'邯郸市\'),
    array(\'id\' => 4, \'pid\' => 2, \'name\' => \'朝阳区\'),
    array(\'id\' => 5, \'pid\' => 2, \'name\' => \'通州区\'),
    array(\'id\' => 6, \'pid\' => 4, \'name\' => \'望京\'),
    array(\'id\' => 7, \'pid\' => 4, \'name\' => \'酒仙桥\'),
    array(\'id\' => 8, \'pid\' => 3, \'name\' => \'永年区\'),
    array(\'id\' => 9, \'pid\' => 1, \'name\' => \'武安市\'),
    array(\'id\' => 10, \'pid\' => 7, \'name\' => \'三街坊\'),
);

//传值引用
function list_to_tree($list,$id=\'id\',$pid=\'pid\',$child=\'_child\',$root=0)
{
    $tree = [];
    if (is_array($list))
    {
        //创建基于主键的数组引用
        $refer = [];
        foreach ($list as $k=>$v)
        {
            $refer[$v[$id]]=&$list[$k];
        }

        foreach ($list as $k=>$v)
        {
            $parent_id = $v[$pid];
            if ($root==$parent_id)
            {
                $tree[]=&$list[$k];
            }
            else
            {
                if (isset($refer[$parent_id]))
                {
                    $parent = &$refer[$parent_id];
                    $parent[$child][]=&$list[$k];
                }
            }

        }


    }


    return $tree;
}
//递归
function getTree($data, $pId)
{

    $tree = array();

    foreach($data as $k => $v)
    {

        if($v[\'pid\'] == $pId)

        {        //父亲找到儿子

            $v[\'_child\'] = getTree($data, $v[\'id\']);

            $tree[] = $v;

            unset($data[$k]);

        }

    }
    return $tree;
}

以上是关于php实现无限级分类的主要内容,如果未能解决你的问题,请参考以下文章

PHP利用递归函数实现无限级分类的方法_php技巧 - PHP

php实现无限级分类

php PHP无限级分类实现

PHP Yii2.0 框架实现无限级分类

PHP迭代与递归实现无限级分类

PHP_递归实现无限级分类