2015-07-01 101 views
1

你好,我需要從其中包含兒童的數據給孩子的父母改變多維數組的結構,它包含有關父母信息多維數組,葉子作爲父鍵的鍵。遞歸迭代

$tab = [ 
     'movies' => [ 
      'action', 
      'drama', 
      'comedy' => [ 
       'romance' => ['90th'], 
       'boring' 
      ] 
     ], 
     'colors' => [ 
      'red'=>'light', 
      'green'=> [ 
       'dark', 
       'light' 
      ], 
      'oragne' 
     ] 
    ]; 

轉移到

 $tab = [ 
     '90th' => [ 
      'romance' => [ 
       'comedy' => 'movies' 
      ] 
     ], 
     'boring' => [ 
      'comedy' => 'movies' 
     ], 
     'comedy' => 'movies', 
     'drama' => 'movies', 
     'action' => 'movies', 
     'light' => [ 
      'red', 
      'green' => 'colors' 
     ], 
     'dark' => [ 
      'green' => 'colors' 
     ], 
     'oragne' => 'colors', 
     'green' => 'colors', 
     'red' 
    ]; 

我知道獲得葉子我可以使用

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($tab), RecursiveIteratorIterator::LEAVES_ONLY) as $key => $value) { 

     $result[$value] = $key; 
    } 

但它不工作,因爲我期望。

回答

0

這是一個非常部分的答案,所以不要期待你的希望。它可能可以擴展來解決你的問題。

爲此,首先您需要'red'=>'light''red'=>['light'}(因此看起來像'romance' => ['90th'])。然後它會爲您提供一系列平面陣列,而不是您想要的深度。此外,它不像你想要的輸出那樣排序。

function insideOut($array, $trail) { 

    foreach($array as $key => $value) { 

    $new_trail = $trail; 

    if(is_array($value)) { 
     $new_trail[] = $key; 
     insideOut($array[$key], $new_trail); 
    } 
    else { 
     $new_trail[] = $value; 
     print_r($new_trail); 
    } 

    } 

} 

insideOut($tab, array()); 

這給出了以下的輸出:

Array 
(
    [0] => movies 
    [1] => action 
) 
Array 
(
    [0] => movies 
    [1] => drama 
) 
Array 
(
    [0] => movies 
    [1] => comedy 
    [2] => romance 
    [3] => 90th 
) 
Array 
(
    [0] => movies 
    [1] => comedy 
    [2] => boring 
) 
Array 
(
    [0] => colors 
    [1] => red 
    [2] => light 
) 
Array 
(
    [0] => colors 
    [1] => green 
    [2] => dark 
) 
Array 
(
    [0] => colors 
    [1] => green 
    [2] => light 
) 
Array 
(
    [0] => colors 
    [1] => oragne 
) 

如果你能代替print_r($new_trail);的東西,給人的線索「深度」,然後將其保存,這個問題就迎刃而解了。

我知道,我知道,沒有太多的答案,我不期望一個綠色的檢查。但我認爲這比放棄它更好地發佈我的(非常少的)進展。

+0

謝謝。我認爲這是一個普遍的問題,我可以用一種「簡單」的方式來做 – malzahar123