2017-02-16 114 views
-1

我有一個數據集或數組,看起來像安排分層數據的級別

[    
    "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'], 
] 

編輯我澄清了源數據,因爲它似乎導致一些混亂

+0

htt p://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ – Barmar

回答

0

我不是一個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)); 
+0

正是我所需要的。謝謝。我會贊成你,但是,你知道,聲譽很低 –

0

在這裏你去:

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