i have a problem. I want to create my navigation (main menu) froom the database.
It works well and also with unlimited parent items. The only problem is the formatting.
The output should look like that:
<li class="sub">
<a class="widgets" href="#">Einstellungen</a>
<ul>
<li class="sub">
<a href="#">Allgemeines<span>6</span></a>
<ul>
<li><a href="">test1</a></li>
</ul>
</li>
<li><a href="">test2</a></li>
</ul>
</li>
I think you can see the structure behind this.
array:
Array
(
[1] => Array
(
[parent_id] => 0
[name] => Hauptseite
[children] => Array
(
)
)
[2] => Array
(
[parent_id] => 0
[name] => Einstellungen
[children] => Array
(
[3] => Array
(
[parent_id] => 2
[name] => Allgemeines
[children] => Array
(
[4] => Array
(
[parent_id] => 3
[name] => test1
[children] => Array
(
)
)
)
)
[5] => Array
(
[parent_id] => 2
[name] => test2
[children] => Array
(
)
)
)
)
)
UPDATE:
function buildList($testArray) {
echo '<ul>';
foreach ($testArray as $id => $menuItem):
if (isset($menuItem['parent_id']) && $menuItem['parent_id'] == 0): // check if it's a parent category
echo '<li class="home"><a class="widgets" href="#">' . $menuItem['name'] . ' (' . $id . ')' . '</a>';
if (isset($menuItem['children'])): // if it has children let's spit them out too
echo '<ul class="child">';
outputChildren($menuItem['children']);
echo '</ul>';
endif;
endif;
if (isset($menuItem['parent_id']) && $menuItem['parent_id'] != 0): // if it's a child let's get it's info
echo '<li class="sub"><a href="#">' . $menuItem['name'] . '</a>';
if (isset($menuItem['children'])): // if there are grandchildren let's get them too
echo '<ul class="child">';
outputChildren($menuItem['children']);
echo '</ul>';
endif;
echo '</li>';
continue;
endif;
if (isset($menuItem['parent_id']) && $menuItem['parent_id'] == 0): // check if it's a parent category
echo '</li>';
endif;
endforeach;
echo '</ul>';
}
function outputChildren($child) {
if (isset($child['name'])):
echo '<li class="sub"><a href="#">' . $child['name'] . '</a>';
if (!empty($child['children'])):
echo '<ul>';
outputChildren($child['children']);
echo '</ul>';
endif;
echo '</li>';
endif;
}
$sites = array();
$sql = 'SELECT menu_id, menu_name, parent_id FROM `' .$_config['prefix']. '_menu`';
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
$sites[(int) $row['menu_id']] = array(
'parent_id' => (int) $row['parent_id'],
'name' => $row['menu_name'],
'children' => array()
);
}
foreach ($sites as $site_id => $site) {
$sites[$site['parent_id']]['children'][$site_id] = & $sites[$site_id];
}
$sites = $sites[0]['children'];
print_r($sites);
echo buildList($sites);
Will output:
<ul>
<li class="home">
<a class="widgets" href="#">Hauptseite (1)</a>
<ul class="child"></ul>
</li>
<li class="home">
<a class="widgets" href="#">Einstellungen (2)</a>
<ul class="child"></ul>
</li>
</ul>
See the first example how it should look like.
Thanks