Skip to content

Instantly share code, notes, and snippets.

@iron-viper
Created April 8, 2016 21:55
Show Gist options
  • Save iron-viper/d8e9a2cc3d633df768832df6c064be1f to your computer and use it in GitHub Desktop.
Save iron-viper/d8e9a2cc3d633df768832df6c064be1f to your computer and use it in GitHub Desktop.
/** PHP function **/
function array_to_tree(array $array, $parent_id = 0)
{
$array = array_combine(array_column ($array, 'id'), array_values($array));
foreach ($array as $k => &$v) {
if (isset($array[$v['parent_id']])) {
$array[$v['parent_id']]['children'][$k] = &$v;
}
unset($v);
}
return array_filter($array, function($v) use ($parent_id) {
return $v['parent_id'] == $parent_id;
});
}
/** SQL get all leaf nodes Мы можем найти все конечные узлы в дереве (т.е. без детей) с помощью **/
SELECT t1.name FROM
category AS t1 LEFT JOIN category as t2
ON t1.category_id = t2.parent
WHERE t2.category_id IS NULL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment