Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Created August 4, 2018 01:27
Show Gist options
  • Save trafficinc/d8c25290df0804351d5d40e66dcec039 to your computer and use it in GitHub Desktop.
Save trafficinc/d8c25290df0804351d5d40e66dcec039 to your computer and use it in GitHub Desktop.
Create menu from array
<?php
$data = array(
array(
'id' => 6,
'parent_id' => 0,
'depth' => 0,
'left' => 1,
'right' => 2,
'title' => 'Home',
'status' => 'published',
'type' => 'Basic'
),
array(
'id' => 2,
'parent_id' => 0,
'depth' => 0,
'left' => 3,
'right' => 4,
'title' => 'Bio',
'status' => 'published',
'type' => 'Basic'
),
array(
'id' => 4,
'parent_id' => 0,
'depth' => 0,
'left' => 5,
'right' => 8,
'title' => 'Press/Reviews',
'status' => 'published',
'type' => 'Press'
),
array(
'id' => 5,
'parent_id' => 4,
'depth' => 1,
'left' => 6,
'right' => 7,
'title' => 'Photo Gallery',
'status' => 'published',
'type' => 'Photo'
),
array(
'id' => 7,
'parent_id' => 0,
'depth' => 0,
'left' => 9,
'right' => 12,
'title' => 'Services',
'status' => 'draft',
'type' => 'Basic'
),
array(
'id' => 3,
'parent_id' => 7,
'depth' => 1,
'left' => 10,
'right' => 11,
'title' => 'Contact',
'status' => 'published',
'type' => 'Contact'
)
);
function make(array $array, $no = 0) {
$child = hasChildren($array, $no);
if (empty($child))
return "";
$content = "<ol>\n";
foreach ( $child as $value ) {
$content .= sprintf("\t<li>%s</li>\n", $value['title']);
$content .= make($array, $value['id']);
}
$content .= "</ol>\n";
return $content;
}
function hasChildren($array, $id) {
return array_filter($array, function ($var) use($id) {
return $var['parent_id'] == $id;
});
}
echo make($data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment