2014-02-23 83 views
0

我有一個像以下「樹」陣列。這是一個導航。現在我想刪除所有級別> = 3.所以我只想得到一個與前兩個級別的數組。有沒有辦法像這樣修剪/縮短陣列。PHP樹陣列刪除水平

你有什麼我可以找的提示嗎?

Array 
(
    [0] => Array 
     (
      [name] => Home 
      [level] => 1 
      [sub] => 
     ) 

    [1] => Array 
     (
      [name] => Products 
      [level] => 1 
      [sub] => Array 
       (
        [56] => Array 
         (
          [name] => Product 1 
          [level] => 2 
          [sub] => Array 
           (
            [61] => Array 
             (
              [name] => Product 1b 
              [target] => 
              [level] => 3 
              [sub] => 
             ) 

           ) 

         ) 

        [57] => Array 
         (
          [name] => Product 2 
          [level] => 2 
          [sub] => 
         ) 

       ) 

     ) 

    [2] => Array 
     (
      [name] => Contact 
      [level] => 1 
      [sub] => 
     ) 

    [3] => Array 
     (
      [name] => Something Else 
      [level] => 1 
      [sub] => 
     ) 

) 

回答

0
$data = [ 
    0 => ['name' => 'Home', 'level' => 1, 'sub' => []], 
    1 => [ 
     'name' => 'Products', 
     'level' => 2, 
     'sub' => [ 
      '56' => [ 
       'name' => 'Product 1', 
       'level' => 2, 
       'sub' => [ 
        '61' => [ 'name' => 'Product 1b', 'target' => '', 'level' => 3, 'sub' => ''], 
       ], 
      ], 
      '57' => ['name' => 'Product 2', 'level' => 2, 'sub' => ''] 
     ] 
    ], 
    2 => ['name' => 'Contact', 'level' => 1, 'sub' => []], 
    3 => ['name' => 'Something Else', 'level' => 1, 'sub' => []] 
]; 

function processArray(&$arr) { 
    foreach ($arr as $key => $array) { 
     if ($array['level'] >= 3) { 
      unset($arr[$key]); 
     } 
     if (!empty($arr[$key]['sub'])) { 
      processArray($arr[$key]['sub']); 
     } 
    } 
} 

processArray($data); 
+0

完美!非常感謝!我認爲參考文獻(&$ arr)是缺失的一點。我以同樣的方式遍歷數組並試圖取消設置數組。但沒有參考它沒有工作。非常感謝! – user3343737