Reputation: 5248
Am building application whitch will show family tree from database using recrusive function. For start everything work fantastic but my function not looping deeper and loop child
of their child
.
On image above looping must also loop Annie
childs Steve
and Rex
.
Check my code:
<?php
$categories = $db->query("SELECT * FROM user");
$data = array();
// build menu
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
// Child recrusive looping
function recrusive_child($childs) {
if(isset($childs)) {
foreach ($childs as $child) {
echo "<li><a href='#'>".$child['username']."</a></li>";
}
}
}
while ($result = $categories->fetch_assoc()) {
$data[] = $result;
}
$tree = buildTree($data);
?>
<div class="tree">
<ul>
<?php foreach ($tree as $item): ?>
<?php if($item['parent'] == null): ?>
<li><a href=""><?= $item['username'];?></a>
<?php if($item['children']): ?>
<ul>
<?php recrusive_child($item['children']); ?>
</ul>
<?php endif; ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</div>
</div>
Upvotes: 0
Views: 66
Reputation: 4350
Make a recursive calling of recrusive_child
(recursive_child?
)
function recrusive_child($childs) {
if(isset($childs)) {
foreach ($childs as $child) {
echo "<li><a href='#'>".$child['username']."</a>";
if ($child['children']){
echo "<ul>";
recrusive_child($child['children']);
echo "</ul>";
}
echo "</li>";
}
}
}
Upvotes: 1
Reputation: 110
Here is a simple example to create recursive category List
<?
function buildTree($parent = 0, $treeArray = '') {
if (!is_array($treeArray))
$treeArray = array();
$sql = "SELECT `cid`, `name`, `parent` FROM `category` WHERE 1 AND `parent` = $parent ORDER BY cid ASC";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
$treeArray[] = "<ul>";
while ($row = mysql_fetch_object($query)) {
$treeArray[] = "<li>". $row->name."</li>";
$treeArray = buildTree($row->cid, $user_tree_array);
}
$treeArray[] = "</ul>";
}
return $treeArray;
}
?>
<ul>
<?php
$returnedData = buildTree();
foreach ($returnedData as $returnedD) {
echo $returnedD;
}
?>
</ul>
Upvotes: 1