Skip to content

Instantly share code, notes, and snippets.

@ixti
Created May 13, 2010 19:39
Show Gist options
  • Save ixti/400346 to your computer and use it in GitHub Desktop.
Save ixti/400346 to your computer and use it in GitHub Desktop.
<?php
$arr = array(
array(
'nid' => 1,
'parentID' => 0
),
array(
'nid' => 2,
'parentID' => 1
),
array(
'nid' => 3,
'parentID' => 2
)
);
print_r(mktree_array($arr));
<?php
/**
* @param array $arr Array to process
* @param integer $id (optional) Base parent ID
* @return array
*/
function mktree_array(&$arr, $id = 0)
{
$result = array();
foreach ($arr as $a) {
if ($id == $a['parentID']) {
$a['children'] = mktree_array($arr, $a['nid']);
$result[] = $a;
}
}
return $result;
}
Array
(
[0] => Array
(
[nid] => 1
[parentID] => 0
[children] => Array
(
[0] => Array
(
[nid] => 2
[parentID] => 1
[children] => Array
(
[0] => Array
(
[nid] => 3
[parentID] => 2
[children] => Array
(
)
)
)
)
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment