Skip to content

Instantly share code, notes, and snippets.

@ravyg
Created March 19, 2012 08:06
Show Gist options
  • Save ravyg/2102108 to your computer and use it in GitHub Desktop.
Save ravyg/2102108 to your computer and use it in GitHub Desktop.
takes in simple array to generate hierarchical nested array #tree #graph
<?php
function hierarchical_array_from_array($farray){
foreach ($flatArray as $key=>$flat) {
$nodes = array();
$tree = array();
foreach ($flatArray as $key=>&$node) {
$node["Children"] = array();
$id = $node["@id"];
$parent_id = $node["@parentId"];
$nodes[$id] =& $node;
if (array_key_exists($parent_id, $nodes)) {
$nodes[$parent_id]["Children"][] =& $node
} else {
$tree[] =& $node;
}
}
return $tree;
}
@ravyg
Copy link
Author

ravyg commented Mar 19, 2012

tree #graph

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment