<?php
/**
* 将数据格式化成树形结构
* @param array $data
* @return array
*/
function getTreeId($data) {
//注意如果你的数组下标默认是0的话,那就要处理一下数组 首先将下标设置为ID
foreach ($data as $v) $data[$v['id']] = $v; unset($data[0]);
foreach ($data as $v)
$data[$v['pid']]['lower'][$v['id']] = &$data[$v['id']];
return isset($data[0]['lower']) ? $data[0]['lower'] : array();
}
$data = 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' => 1, 'name' => '海珠区'),
7 => array('id' => 7, 'pid' => 1, 'name' => '番禺区'),
8 => array('id' => 8, 'pid' => 3, 'name' => '天河美景1'),
9 => array('id' => 9, 'pid' => 3, 'name' => '天河美景2'),
10 => array('id' => 10, 'pid' => 6, 'name' => '广州塔'),
11 => array('id' => 11, 'pid' => 4, 'name' => '罗湖美景1'),
12 => array('id' => 12, 'pid' => 4, 'name' => '罗湖美景2'),
13 => array('id' => 13, 'pid' => 5, 'name' => '福田美景')
);
echo "<pre>";
print_r(getTreeId($data));当然你也可以使用 递归来实现无限级分类:http://www.blogxuan.com/php/show/198.html