【发布时间】:2012-07-25 08:53:46
【问题描述】:
我一直试图弄清楚如何使用我遇到的各种示例从数据库中创建一个树视图,但到目前为止还没有成功。
我的数据库结构如下:
id | parent_id | title | Urgency(紧急未落实)
最终结果应该生成一个树形视图,其中紧急程度的值决定了用于每个项目的图像。
我最近尝试使用的代码是:
<hmtl>
<body>
<?php
function get_children($parent, $level = 1)
{
$result = mysql_query('SELECT * FROM treeview_items WHERE parent_id = '.$parent);
$result2 = mysql_fetch_array($result, MYSQL_ASSOC);
#for avoiding some errors
if(mysql_num_rows($result) > 0)
#start the list
echo '<ul>';
foreach($result2 as $row) {
#print the item, you can also make links out of these
echo '<li>'.$row['title'].'</li>';
#this is similar to our last code
#this function calls it self, so its recursive
get_children($row['id'], $level+1);
}
#close the list
echo '</ul>';
}
mysql_connect('localhost', 'root');
mysql_select_db('test');
$result = mysql_query('SELECT * FROM treeview_items');
$result2 = mysql_fetch_array($result, MYSQL_ASSOC);
#for avoiding some errors
if(mysql_num_rows($result) > 0) {
#start the list
echo '<ul>';
foreach($result2 as $row) {
#print the item, you can also make links out of these
echo '<li>'.$row['title'].'</li>';
#recursive function(made in next step) for getting all the subs by passing
id of main item
get_children($row['id']);
}
#end the list
echo '</ul>';
#some message if the database is empty
}
else echo 'No Items';
#clear the memory
mysql_free_result($result);
?>
</body>
<html>
基本上我的代码不起作用。我可以尝试解决什么问题?
编辑
我更改了一些代码以修复几个错误 所以现在我看到的是:
- 1
- 2
- 5
警告:在第 13 行的 C:\Program Files\EasyPHP-5.3.9\www\test.php 中为 foreach() 提供的参数无效
重复 100 次直到中止。不知道为什么,因为代码中的foreach()都是一样的,但是函数里面的那个不行。
【问题讨论】:
-
#this function calls it self, so its recursive:) -
在执行 foreach 之前(失败),您能否执行
print_r($result2); exit();- 这将向我们展示数组中的实际内容并在该点之后终止脚本(此时更易于调试) -
Array ( [id] => 2 [parent_id] => 1 [title] => sub header 1 ) 当我在 foreach() 上方输入您的代码时显示
-
看这个...它对你有帮助stackoverflow.com/questions/10215980/…
-
@jey 谢谢,您应该将其发布为答案,以便我接受! :)
标签: php mysql database treeview