-
-
Save voidnerd/91ccf96fbc680f176c2047a2658449a8 to your computer and use it in GitHub Desktop.
PHP: convert object / array to tree structure
This file contains hidden or 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 | |
/* | |
* 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