Skip to content

Instantly share code, notes, and snippets.

@adopabianko
Created June 30, 2021 08:20
Show Gist options
  • Select an option

  • Save adopabianko/4bfc11690b2e2a6de3688a6dfafedc80 to your computer and use it in GitHub Desktop.

Select an option

Save adopabianko/4bfc11690b2e2a6de3688a6dfafedc80 to your computer and use it in GitHub Desktop.
<?php
function sortMenu($data, $parent = 0, $space = '') {
if (isset($data[$parent])) {
$menu = '';
foreach($data[$parent] as $val) {
$newSpace = $space.'.';
$child = sortMenu($data, $val[0], $newSpace);
$menu .= $newSpace.' ';
$menu .= $val[2]."\n";
if ($child) {
$menu .= $child;
}
}
return $menu;
} else {
return false;
}
}
function sortByOrder($a, $b) {
return $a[3] - $b[3];
}
$menuArr = [
[1, 0, "Beranda", 0],
[2, 0, "Product", 2],
[3, 2, "Product 1", 0],
[4, 2, "Product 2", 1],
[5, 2, "Product 3", 2],
[6, 0, "About Us", 1],
[7, 6, "Contact Us", 0],
[8, 5, "Product 3.1", 0],
[9, 2, "Product 4", 3]
];
usort($menuArr, "sortByOrder");
$data = [];
for($i = 0; $i < count($menuArr); $i++) {
$parent = $menuArr[$i][1];
$data[$parent][] = $menuArr[$i];
}
echo sortMenu($data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment