How can I transform array#1 into the array#2 structure using php ?
The first Array is the results of a database query on a list of Organisms, each organism is classified
I don't think this will be super-efficient for really large arrays, but it works for your scenario (here's a sample).
$array = ...
$levels = array('Rank_Order', 'Rank_Family', 'Rank_Genus', 'Rank_Species');
function get_children($parent, $lev, $orig, $levels){
if($lev + 1 > count($levels)){
return array();
}
$seen = array();
$children = array();
foreach($orig as $node){
if($node[$levels[$lev]] == $parent && !in_array($node[$levels[$lev+1]], $seen)){
$seen[] = $node[$levels[$lev+1]];
$children[] = get_children($node[$levels[$lev+1]], $lev+1, $orig, $levels);
}
}
return array('name' => $parent, 'children' => $children);
}
function hier($orig, $levels){
$seen = array();
$result = array();
foreach($orig as $node){
if(!in_array($node[$levels[0]], $seen)){
$seen[] = $node[$levels[0]];
$result[] = get_children($node[$levels[0]], 0, $orig, $levels);
}
}
return $result;
}
print_r($array);
print_r(hier($array, $levels));