1、
function generateTree($items){
$tree = array();
foreach($items as $item){
if(isset($items[$item['pid']])){
$items[$item['pid']]['son'][] = &$items[$item['id']];
}else{
$tree[] = &$items[$item['id']];
}
}
return $tree;
}
$items = array(
1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
);
print_r(generateTree($items));
2、
function getTree($data, $pId=0)
{
$tree = '';
foreach($data as $k => $v){
if($v['pid'] == $pId){
//父亲找到儿子
$v['pid'] = getTree($data, $v['id']);
$tree[] = $v;
//unset($data[$k]);
}
}
return $tree;
}
$categories = array(
array('id'=>1,'name'=>'电脑','pid'=>0),
array('id'=>2,'name'=>'手机','pid'=>0),
array('id'=>3,'name'=>'笔记本','pid'=>1),
array('id'=>4,'name'=>'台式机','pid'=>1),
array('id'=>5,'name'=>'智能机','pid'=>2),
array('id'=>6,'name'=>'功能机','pid'=>2),
array('id'=>7,'name'=>'超级本','pid'=>3),
array('id'=>8,'name'=>'游戏本','pid'=>3),
);