按级别排列分层数据

时间:2017-02-16 21:13:48

标签: php mysql arrays recursion

我有一个类似于

的数据集或数组
[               
  "foo",        
  "bar",        
  [             
    "gum",      
    "ball",     
    [           
      "fat",    
      "rubber", 
    ],          
    "zoo",      
    "topia",    
  ],            
  "ant",        
  "elephant",   
  "grass",      
  [             
    "hopper",   
  ],            
]               

我想要一个函数按照它们的级别或深度对它们进行分组。类似的东西:

[
   "level 1" => ['foo','bar','ant','elephant','grass'],
   "level 2" => ['gum','ball','zoo','topia','hopper'],
   "level 3" => ['fat','rubber'],
]

编辑我澄清了源数据,因为它似乎引起了一些混乱

2 个答案:

答案 0 :(得分:1)

我不是SQL大师,你没有展示任何关于数据库的内容,所以这里是一个递归的PHP函数:

function get_levels($array, $level=1) {

    $result = array();

    foreach($array as $value) {
        if(is_array($value)) {
            $result += get_levels($value, $level+1);
        } else {
            $result[$level][] = $value;
        }
    }
    return $result;
}

print_r(get_levels($array));

答案 1 :(得分:0)

你走了:

SELECT LENGTH(value) - LENGTH(REPLACE(value, '-', '')) as level, GROUP_CONCAT(REPLACE(value, '-', '')) as groups
FROM test
GROUP BY level;