标签:
/* CREATE TABLE `category` ( `id` int(11) NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL DEFAULT ‘0‘, `cname` varchar(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; **/ mysql_connect(‘localhost‘, ‘root‘, ‘‘) or die(‘Cannot connected to mysql server‘); mysql_select_db(‘security‘); mysql_query(‘set names utf8‘); $sql = ‘select * from category‘; $rs = mysql_query($sql); $categories = array(); while ($row = mysql_fetch_assoc($rs)) { $categories[] = $row; } //$arr = get_comment($categories); //echo get_tree($arr); echo ‘<select>‘; treew($categories); echo ‘</select>‘; function treew($arr, $pid = 0, $n = 0){ $s = str_pad(‘‘,$n,‘-‘); $s = str_replace(‘-‘, ‘ ‘, $s); for ($i=0; $i < count($arr); $i++) { if ($pid == $arr[$i][‘pid‘]) { echo ‘<option>‘ . $s .$arr[$i][‘cname‘]. "</option>\n"; treew($arr, $arr[$i][‘id‘], $n+1); } } } function get_comment($categories, $pid = 0) { $array = array(); foreach ($categories as $key => $value) { if ($pid == $value[‘pid‘]) { $value[‘son‘] = get_comment($categories, $value[‘id‘]); $array[] = $value; } } return $array; } function get_tree($arr) { $html = ‘‘; foreach ($arr as $key => $value) { if (empty($value[‘son‘])) { $html .= $value[‘cname‘] . ‘<br/>‘; } else { $html .= $value[‘cname‘] . get_tree($value[‘son‘]) . ‘<br/>‘; } } return $html; }
标签:
原文地址:http://www.cnblogs.com/adtuu/p/4799903.html