//无限级分类
$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;
}

hea7r9o4
1 声望0 粉丝