我正在用php CodeIgniter做一个项目,它有一个表,所有的attributes_values都可以保存在其中,并且它的设计使得它可以在相同的tbl中拥有它的孩子。数据库结构为
fld_id fld_value fld_attribute_id fld_parent_id
1 att-1 2 0
2 att-2 2 0
3 att-1_1 2 1
4 att-1_2 2 1
5 att-1_1_1 2 3上面的att-1是任何属性的属性值,它有两个父id为1的子表att-1_1和att-1_2。att-1_1也有它的子表att-1_1_1,parent_id为3。fld_parent_id是同一个表的fld_id,表示它的子表。现在我想在树形结构中展示这一点,如下所示
Level1 level2 level3 ..... level n
att-1
+------att-1_1
| +------att-1_1_1
+------att-1_2
att-2并且该树结构可以变化到n级。带有父id的属性值在第一级,我从第一级提取了这些值,现在我必须检查它的子级,如果它有更多的子级,就像上面那样显示它的子级。我使用了一个帮助器,并尝试使其递归,但这并没有发生。那么我该怎么做呢:代码如下
foreach($attributes_values->result() as $attribute_values){
if($attribute_values->fld_parent_id==0 && $attribute_values->fld_attribute_id==$attribute->fld_id){
echo $attribute_values->fld_value.'<br/>';
$children = get_children_by_par_id($attribute_values->fld_id); //helper function
echo '<pre>';
print_r($children);
echo '</pre>';
}
}帮助器代码如下:
function get_children_by_par_id($id){ //parent id
$children = get_children($id);
if($children->num_rows()!=0){
foreach($children->result() as $child){
get_children_by_par_id($child->fld_id);
return $child;
}
}
}
function get_children($id){
$CI = get_instance();
$CI->db->where('fld_parent_id',$id);
return $CI->db->get('tbl_attribute_values');
}请帮帮我.............
发布于 2013-04-30 17:34:11
递归的关键是“无休止”的调用。这可以通过调用self的函数来完成。
所以
function get_children($parent_id)
{
// database retrieve all stuff with the parent id.
$children = Array();
foreach($results as $result)
{
$result['children'] = get_children($result['id']);
$children[] = $result;
}
return $children;
}发布于 2013-04-30 17:36:48
或者使用内置到PHP中的SPL库PHP recursive iterator
https://stackoverflow.com/questions/16296459
复制相似问题