Skip to content

Instantly share code, notes, and snippets.

@Ichinya
Created June 3, 2021 10:23
Show Gist options
  • Save Ichinya/3869007aa9881ae562a7414d28bee692 to your computer and use it in GitHub Desktop.
Save Ichinya/3869007aa9881ae562a7414d28bee692 to your computer and use it in GitHub Desktop.
генерирует древовидную структуру массива. Элемент привязывается по связке id=> parent_id, добавляется к родительскому элементу в поле childs.
<?php
function generate_tree($data, $parent = 'parent_id', $childs = 'childs')
{
$tree = array();
foreach ($data as $id => &$node)
{
if (!$node[$parent] || !isset($data[$node[$parent]]))
{
unset($node[$parent]);
$tree[$id] = &$node;
}
else
{
$parent_id = $node[$parent];
unset($node[$parent]);
$data[$parent_id][$childs][$id] = &$node;
}
}
return $tree;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment