首先创建无限分类的数据表,我这里采用的是id、name、pid这种类型(当然还有很多种无限分类的方式了,比如:id、name、pid、path。left、right左右节点的形式)

CREATE TABLE `class` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(128) default NULL,
`pid` int(11) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8                                                         

我这里就用数组来模拟,不添加数据了。。。

$items = array(
1 => array('sid' => 1, 'pid' => 0, 'name' => '江西省'),
2 => array('sid' => 2, 'pid' => 0, 'name' => '黑龙江省'),
3 => array('sid' => 3, 'pid' => 1, 'name' => '南昌市'),
4 => array('sid' => 4, 'pid' => 2, 'name' => '哈尔滨市'),
5 => array('sid' => 5, 'pid' => 2, 'name' => '鸡西市'),
6 => array('sid' => 6, 'pid' => 4, 'name' => '香坊区'),
7 => array('sid' => 7, 'pid' => 4, 'name' => '南岗区'),
8 => array('sid' => 8, 'pid' => 6, 'name' => '和兴路'),
9 => array('sid' => 9, 'pid' => 7, 'name' => '西大直街'),
10 => array('sid' => 10, 'pid' => 8, 'name' => '东北林业大学'),
11 => array('sid' => 11, 'pid' => 9, 'name' => '哈尔滨工业大学'),
12 => array('sid' => 12, 'pid' => 8, 'name' => '哈尔滨师范大学'),
13 => array('sid' => 13, 'pid' => 1, 'name' => '赣州市'),
14 => array('sid' => 14, 'pid' => 13, 'name' => '赣县'),
15 => array('sid' => 15, 'pid' => 13, 'name' => '于都县'),
16 => array('sid' => 16, 'pid' => 14, 'name' => '茅店镇'),
17 => array('sid' => 17, 'pid' => 14, 'name' => '大田乡'),
18 => array('sid' => 18, 'pid' => 16, 'name' => '义源村'),
19 => array('sid' => 19, 'pid' => 16, 'name' => '上坝村'),
20 => array('sid' => 20, 'pid' => 0, 'name' => '广东省'),
21 => array('sid' => 21, 'pid' => 20, 'name' => '广州市'),
22 => array('sid' => 22, 'pid' => 20, 'name' => '东莞市'),
);

代码如下:

$t = array();
foreach ($items as $id => $item) {
  echo $item['pid'];
  if ($item['pid']) {
    $items[$item['pid']][$item['sid']] = &$items[$item['sid']];
    $t[] = $id;
  }
}

foreach($t as $u) {
  unset($items[$u]);
}
echo "

";
print_r($items);
echo "
登录后复制
";

打印的结果如下:

以上代码是我在网上搜集的,觉得比较经典,而且相对于其他的来说,代码量也少。。

感谢网络中的大神能和我们一起分享。。。

09-14 14:20