php树状结构

文章描述:

php把数组数据处理成树状结构

数组

$member = array(
    array('id'=>1, 'pid'=>0, 'nickname' => '手机'),
    array('id'=>2, 'pid'=>1, 'nickname' => 'oppo'),
    array('id'=>3, 'pid'=>1, 'nickname' => 'iphone'),
    array('id'=>4, 'pid'=>2, 'nickname' => 'oppo R11s'),
    array('id'=>5, 'pid'=>3, 'nickname' => 'iphone4'),
    array('id'=>6, 'pid'=>3, 'nickname' => 'iphone5'),
    array('id'=>7, 'pid'=>3, 'nickname' => 'iphone6'),
    array('id'=>8, 'pid'=>0, 'nickname' => '电脑')
);

方法

function getTree($data, $pId)
    {
        $tree = array();
        foreach($data as $k => $v)
        {
            if($v['pid'] == $pId)
            {
                //父亲找到儿子
                $v['children'] = getTree($data, $v['id']);
                
                $tree[] = $v;
            }
        }
        return $tree;
    }

使用

echo "<pre>";
$lists = getTree($member,0);
print_r($lists);

 

发布时间:2021/11/10

发表评论