Created
July 18, 2013 08:19
-
-
Save jiromm/6027641 to your computer and use it in GitHub Desktop.
Category Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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