php递归无限级分类的问题,有高手来解答下
数组如下$arr=array(1=>array('id'=>1,'pid'=>0,'name'=>'广东省'),2=>array('id'=>2,'pid'=>0,'na...
数组如下
$arr = 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' => '深圳市'),
)
怎么将$arr数组拆解为下面这种形式:
Array(
[0] => Array(
[id] => 1,
[pid] => 0,
[name] => 广东省,
[son] => Array(
[0] => Array(
[id] => 3
[pid] => 1
[name] => 广州市
[son] => Array(
[0] => Array(
[id] => 4
[pid] => 3
[name] => 深圳市
)
)
)
)
[1] => Array(
[id] => 2,
[pid] => 0,
[name] => 广西省
)
)
希望知道的人能帮我解答下,不胜感激。因为没玩过问答所以也没什么积分。。。。. 展开
$arr = 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' => '深圳市'),
)
怎么将$arr数组拆解为下面这种形式:
Array(
[0] => Array(
[id] => 1,
[pid] => 0,
[name] => 广东省,
[son] => Array(
[0] => Array(
[id] => 3
[pid] => 1
[name] => 广州市
[son] => Array(
[0] => Array(
[id] => 4
[pid] => 3
[name] => 深圳市
)
)
)
)
[1] => Array(
[id] => 2,
[pid] => 0,
[name] => 广西省
)
)
希望知道的人能帮我解答下,不胜感激。因为没玩过问答所以也没什么积分。。。。. 展开
2015-06-22
展开全部
<?php
$arr = 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' => '深圳市'),
);
function generateTree($items){
foreach($items as $item){
$items[$item['pid']]['son'][] = &$items[$item['id']];
}
return isset($items[0]['son']) ? $items[0]['son'] : array();
}
print_r(generateTree($arr));
?>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询