以下函数,其中$data
由表示从数据库中提取的结果的对象/数组组成:
public function build_tree($data, $parent_id = '0')
{
$tree = array();
foreach ($data as $key => $value) {
if ($value->parent_id === $parent_id) { //build array
$tree[] = $value;
// using recursion
$children = $this->build_tree($data, $value->id);
if ($children) { // build array
$tree[] = $children;
}
}
}
return $tree;
}
给我嵌套数组:
array (size=4)
0 =>
object(stdClass)[33]
public 'id' => string '16' (length=2)
public 'parent_id' => string '0' (length=1)
public 'title' => string 'Test 3' (length=6)
public 'excerpt' => string '' (length=0)
public 'content' => string '' (length=0)
public 'order' => string '1' (length=1)
1 =>
array (size=2)
0 =>
object(stdClass)[35]
public 'id' => string '18' (length=2)
public 'parent_id' => string '16' (length=2)
public 'title' => string '- Novo' (length=6)
public 'excerpt' => string 'dfgdfg' (length=6)
public 'content' => string 'dfgdfg' (length=6)
public 'order' => string '6' (length=1)
1 =>
array (size=1)
0 =>
object(stdClass)[31]
public 'id' => string '14' (length=2)
public 'parent_id' => string '18' (length=2)
public 'title' => string '- - Test 1.1.1' (length=14)
public 'excerpt' => string '' (length=0)
public 'content' => string '' (length=0)
public 'order' => string '0' (length=1)
2 =>
object(stdClass)[34]
public 'id' => string '17' (length=2)
public 'parent_id' => string '0' (length=1)
public 'title' => string 'Test 666' (length=8)
public 'excerpt' => string '' (length=0)
public 'content' => string '' (length=0)
public 'order' => string '8' (length=1)
3 =>
array (size=1)
0 =>
object(stdClass)[32]
public 'id' => string '15' (length=2)
public 'parent_id' => string '17' (length=2)
public 'title' => string '- Test 2' (length=8)
public 'excerpt' => string '' (length=0)
public 'content' => string '' (length=0)
public 'order' => string '4' (length=1)
是否可以在不嵌套的情况下构建新阵列?但仍然保持正确的秩序和父子关系?这意味着所有的子元素仍然会在其父索引之后但没有嵌套?
答案 0 :(得分:0)
只需遍历结果树:
Enter
那应该做的。
答案 1 :(得分:0)
如果您想要返回平面列表,只需替换:
#footer .lv2 > li > a:hover:after
background-color: tomato;
}
#footer .lv2 > li > a:hover
background-color: tomato;
}
使用:
$children = $this->build_tree($data, $value->id);