图文课程 职群旗下

  1. 首页
  2. 所有分类
  3. PHP
  4. 生成树型结构(比如省市区)

生成树型结构(比如省市区)


<?phpheader("Content-type: text/html;
charset=utf-8");
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;
}

//需要注意的一点,数组的key值必须与id值保持一致
$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' =>
'安庆市'),);
echo "<pre>";
print_r(generateTree($items));

 

上面方法的优化:

<?phpheader("Content-type: text/html;
charset=utf-8");
function generateTree($items){foreach($items as $item)$items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
return isset($items[0]['son']) ? $items[0]['son'] : array();
}


//
需要注意的一点,数组的key值必须与id保持一致$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' =>
'安庆市'),);
echo "<pre>";
print_r(generateTree($items));
View Code

 

结果:

猜你喜欢
JVM运行时内存结构 用户线程和内核线程的区别
[MySQL Reference Manual] 20 分区 关于UIImage类的对象两种初始化方法的区别
.replace(R.id.container, new User()).commit();/The method replace(int, Fragment) in the type Fragmen Mysql 表分区
$(document).ready()即$()方法和window.onload方法的比较 "The request sent by the client was syntactically incorrect ()"问题定位及解决:
你可能不知道的行内元素和块元素最主要的区别 Servlet的2中初始化方法---init()和int(ServletConfig config)