Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[PHP] Пример рекурсивного вывода меню
<?php
$nav = [
[
'name' => 'Home',
'title' => 'Homepage',
// ...something else...
'sub' => [
[
'name' => 'sub11',
'title' => null,
// ...something else...
'sub' => [
[
'name' => 'sub111',
'title' => 'This is the Sub 111',
],
],
],
[
'name' => '',
'title' => 'This is the Sub 12',
'sub' => [
[
'name' => null,
'title' => 'This is the Sub 121',
],
],
],
],
],
[
'name' => 'sub2',
'title' => 'This is the Sub 2',
'sub' => [
[
'name' => 'sub21',
'title' => 'This is the Sub 21',
],
],
],
];
function has_submenu($menu): bool
{
return is_array($menu)
&& isset($menu['sub'])
&& !empty($menu['sub'])
&& is_array($menu['sub']);
}
function print_menu(array $menu, int $level = 0)
{
$ident = '';
foreach ($menu as $element) {
$ident = str_pad($ident, $level);
echo $ident.'Name: '.($element['name'] ?? '(empty)').PHP_EOL;
echo $ident.'Title: '.($element['title'] ?? '(empty)').PHP_EOL;
echo $ident.'Url: '.($element['url'] ?? '(empty)').PHP_EOL;
echo $ident.'Submenu:'.(has_submenu($element) ? '' : ' (empty)' ).PHP_EOL;
if (has_submenu($element)) {
print_menu($element['sub'], $level += 4);
}
$level -= 4;
}
}
print_menu($nav);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment