rearrange a php array into a nested hierarchical array

前端 未结 1 1812
逝去的感伤
逝去的感伤 2021-01-25 00:51

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

相关标签:
1条回答
  • 2021-01-25 01:12

    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));
    
    0 讨论(0)
提交回复
热议问题