/*
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 ‘‘;
treew($categories);
echo ‘‘;
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 ‘‘ . $s .$arr[$i][‘cname‘]. "\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‘] . ‘
‘;
} else {
$html .= $value[‘cname‘] . get_tree($value[‘son‘]) . ‘
‘;
}
}
return $html;
}
原文:http://www.cnblogs.com/adtuu/p/4799903.html