Skip to content

Instantly share code, notes, and snippets.

@jiromm
Created July 18, 2013 08:19
Show Gist options
  • Save jiromm/6027641 to your computer and use it in GitHub Desktop.
Save jiromm/6027641 to your computer and use it in GitHub Desktop.
Category Tree
<?php
$nodeList = array();
$tree = array();
$query = mysql_query("SELECT category_id, name, parent FROM categories ORDER BY parent");
while ($row = mysql_fetch_assoc($query)){
$nodeList[$row['category_id']] = array_merge($row, array('children' => array()));
}
mysql_free_result($query);
foreach ($nodeList as $nodeId => &$node) {
if (!$node['parent'] || !array_key_exists($node['parent'], $nodeList)) {
$tree[] = &$node;
} else {
$nodeList[$node['parent']]['children'][] = &$node;
}
}
unset($node);
unset($nodeList);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment