Skip to content

Instantly share code, notes, and snippets.

@tarnfeld
Created August 27, 2011 02:16
Show Gist options
  • Save tarnfeld/1174863 to your computer and use it in GitHub Desktop.
Save tarnfeld/1174863 to your computer and use it in GitHub Desktop.
<?php
class Menu
{
public static function get()
{
$results = DB::query('SELECT * FROM `menu_items` ORDER BY parent_id IS NULL DESC, parent_id ASC, position ASC')->execute()->as_array();
return static::html(static::children($results));
}
protected static function children(array $rows)
{
$x = array();
foreach($rows as $k => $row)
{
// Top Level
if ($row['parent_id'] == NULL)
{
$x[$row['id']] = $row;
unset($rows[$k]);
}
else if (isset($x[$row['parent_id']]))
{
$x[$row['parent_id']]['children'][] = $row;
unset($rows[$k]);
}
else
{
die('wtf is going on here?!');
}
}
return $x;
}
protected static function html(array $items)
{
$html = '';
foreach($items as $item)
{
$html .= '<li>' . $item['title'];
if (isset($item['children']))
{
$html .= '<ul>' . static::html($item['children']) . '</ul>';
}
$html .= '</li>';
}
return $html;
}
}
<ul><?=Menu::get()?></ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment