Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Forked from vyspiansky/build-tree.php
Created September 17, 2018 13:52
Show Gist options
  • Save voidnerd/91ccf96fbc680f176c2047a2658449a8 to your computer and use it in GitHub Desktop.
Save voidnerd/91ccf96fbc680f176c2047a2658449a8 to your computer and use it in GitHub Desktop.
PHP: convert object / array to tree structure
<?php
/*
* Source: http://goo.gl/p2GybZ
*/
// for object
function buildTree($items) {
$childs = array();
foreach($items as $item)
$childs[$item->parent_id][] = $item;
foreach($items as $item) if (isset($childs[$item->id]))
$item->childs = $childs[$item->id];
return $childs[0];
}
// or array version
function buildTree($items) {
$childs = array();
foreach($items as &$item) $childs[$item['parent_id']][] = &$item;
unset($item);
foreach($items as &$item) if (isset($childs[$item['id']]))
$item['childs'] = $childs[$item['id']];
return $childs[0];
}
// usage:
$tree = buildTree($items);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment