私は問題があります。データベースからナビゲーション (メイン メニュー) を作成したいと考えています。
それはうまく機能し、無制限の親アイテムでも機能します。唯一の問題はフォーマットです。
出力は次のようになります。
<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>
これで構造が見えてくると思います。
配列:
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
(
)
)
)
)
)
アップデート:
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);
出力します:
<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>
最初の例を参照してください。
ありがとう