樹形陣列 php,php 樹形陣列

2021-10-25 20:34:04 字數 1797 閱讀 2927

* 樹形陣列

//方法一

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 gentree9($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' => 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' => '上壩村'),

echo '

';
var_dump(gentree5($items));

var_dump(gentree9($items));

樹形資料轉換

測試資料 create table project id int,name nvarchar 20 parent id int insert project select 1,所有專案 null union all select 2,專案1 1 union all select 3,專案2 1 cr...

樹形資料轉換

測試資料 create table project id int,name nvarchar 20 parent id int insert project select 1,所有專案 null union all select 2,專案1 1 union all select 3,專案2 1 cr...

樹形資料轉換

測試資料 create table project id int,name nvarchar 20 parent id int insert project select 1,所有專案 null union all select 2,專案1 1 union all select 3,專案2 1 cr...