你好我正在努力实现这一目标
http://phpfiddle.org/main/code/jw3-s1j
实际上我认为它工作得很好..但是你不能像之前的例子那样区分一个类别和一个子类别..
那么我怎样才能有一个里面有一棵树的选择框???
<?PHP
$result = mysql_query("SELECT id, parent_id, name FROM category")or trigger_error('Query failed: ' . mysql_error(), E_USER_ERROR);; // This line executes the MySQL query that you typed above
$datas = array(); // make a new array to hold all your data
while($row = mysql_fetch_assoc($result)) {
$datas[] = $row;
}
function generatePageTree($datas, $depth = 0, $parent = 0){
if($depth > 1000) return ''; // Make sure not to have an endless recursion
$tree = '';
for($i=0, $ni=count($datas); $i < $ni; $i++){
if($datas[$i]['parent_id'] == $parent){
$tree .= str_repeat('-', $depth);
$tree .= '<option value=\''.$datas[$i]['name'] . '\'>'.$datas[$i]['name'] . '</option><br/>';
$tree .= generatePageTree($datas, $depth+1, $datas[$i]['id']);
}
}
return $tree;
}
echo '<select>';
echo(generatePageTree($datas));
echo '</select>';
?>
解决了!!
固定代码:
function generatePageTree($datas, $depth = 0, $parent = 0){
if($depth > 1000) return ''; // Make sure not to have an endless recursion
$tree = '';
for($i=0, $ni=count($datas); $i < $ni; $i++){
if($datas[$i]['parent_id'] == $parent){
$tree .= str_repeat('-', $depth);
$tree .= '<option value=\''.$datas[$i]['name'] . '\'>'.str_repeat('-', $depth).$datas[$i]['name'] . '</option><br/>';
$tree .= generatePageTree($datas, $depth+1, $datas[$i]['id']);
}