首先創建無限分類的數據表,我這裡采用的是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 "<pre>";
print_r($items);
echo "</pre>";
打印的結果如下:
以上代碼是我在網上搜集的,覺得比較經典,而且相對於其他的來說,代碼量也少。。
感謝網絡中的大神能和我們一起分享。。。