参考
1. http://www.oschina.net/code/snippet_98719_11296
2. http://www.oschina.net/code/snippet_173183_11767
[1] 语句 $tree[] = &$items[$item['id']]; 这里把不存在的键值、内容加上了,如下例中的键值4,但是无法判断其父类,会将其判断为根id,去掉不要;
[2] 考虑到字段名称问题,使用[1]的参数模式,添加分类id和父类pid设置,同时处理一下取得的数据;
实例如下,从表中取得所有分类数据保存到$rows,已考虑添加顺序和删除记录问题
<?php /* * php无限分类数据树形格式化 * * 此方法由 mantye 提供 * http://my.oschina.net/u/223350 * @date 2013-07-22 **/ function genTree($rows, $id='id', $pid='pid') { $items = array(); foreach ($rows as $row) $items[$row[$id]] = $row; foreach ($items as $item) $items[$item[$pid]]['son'][$item[$id]] = &$items[$item[$id]]; return isset($items[0]['son']) ? $items[0]['son'] : array(); } $rows = array( array('id' => 111, 'pid' => 0, 'name' => '江西省'), array('id' => 5, 'pid' => 2, 'name' => '鸡西市'), array('id' => 2, 'pid' => 0, 'name' => '黑龙江省'), array('id' => 3, 'pid' => 111, 'name' => '南昌市'), //array('id' => 4, 'pid' => 2, 'name' => '哈尔滨市'), array('id' => 6, 'pid' => 4, 'name' => '香坊区'), array('id' => 27, 'pid' => 4, 'name' => '南岗区'), array('id' => 8, 'pid' => 6, 'name' => '和兴路'), array('id' => 9, 'pid' => 27, 'name' => '西大直街'), array('id' => 10, 'pid' => 8, 'name' => '东北林业大学'), array('id' => 11, 'pid' => 9, 'name' => '哈尔滨工业大学'), array('id' => 12, 'pid' => 8, 'name' => '哈尔滨师范大学'), array('id' => 13, 'pid' => 111, 'name' => '赣州市'), array('id' => 14, 'pid' => 13, 'name' => '赣县'), array('id' => 15, 'pid' => 13, 'name' => '于都县'), array('id' => 16, 'pid' => 14, 'name' => '茅店镇'), array('id' => 17, 'pid' => 14, 'name' => '大田乡'), array('id' => 18, 'pid' => 16, 'name' => '义源村'), array('id' => 19, 'pid' => 16, 'name' => '上坝村') ); echo '<pre>'; $rows = genTree($rows); print_r($rows); ?>