php數組遞迴方法

來源:互聯網
上載者:User
$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' => 2, 'name' => '哈爾濱市'),
5 => array('id' => 5, 'pid' => 2, 'name' => '雞西市'),
6 => array('id' => 6, 'pid' => 4, 'name' => '香坊區'),
7 => array('id' => 7, 'pid' => 4, 'name' => '南崗區'),
8 => array('id' => 8, 'pid' => 6, 'name' => '和興路'),
9 => array('id' => 9, 'pid' => 7, 'name' => '西大直街'),
10 => array('id' => 10, 'pid' => 8, 'name' => '東北林業大學'),
11 => array('id' => 11, 'pid' => 9, 'name' => '哈爾濱工業大學'),
12 => array('id' => 12, 'pid' => 8, 'name' => '哈爾濱師範大學'),
13 => array('id' => 13, 'pid' => 1, 'name' => '贛州市'),
14 => array('id' => 14, 'pid' => 13, 'name' => '贛縣'),
15 => array('id' => 15, 'pid' => 13, 'name' => '于都縣'),
16 => array('id' => 16, 'pid' => 14, 'name' => '茅店鎮'),
17 => array('id' => 17, 'pid' => 14, 'name' => '大田鄉'),
18 => array('id' => 18, 'pid' => 16, 'name' => '義源村'),
19 => array('id' => 19, 'pid' => 16, 'name' => '上壩村'),
);

方法一;
function genTree5($items) {
foreach ($items as $item)
$items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
return isset($items[0]['son']) ? $items[0]['son'] : array();
}

方法二:
function findChild($arr,$id){
$childs=array();
foreach ($arr as $k => $v){
if($v['pid']== $id){
$childs[]=$v;
}
}
// echo "<pre>";print_r($childs);die();
return $childs;
}

function build_tree($root_id){
global $items;
$childs =array();
$childs=findChild($items,$root_id);
// print_r($childs);
// die();
if(empty($childs)){
return null;
}
foreach ($childs as $k => $v){
$rescurTree=build_tree($v['id']);
if( null != $rescurTree){
$childs[$k]['son']=$rescurTree;
}
}
return $childs;
}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.