2017-09-20 57 views
3

我想通過點分隔鍵刪除特定的子陣列。下面是一些工作(是它的工作,但甚至還沒有接近一個很好的解決方案)代碼:通過點分隔鍵刪除多維數組中的子樹

$Data = [ 
       'one', 
       'two', 
       'three' => [ 
        'four' => [ 
         'five' => 'six', // <- I want to remove this one 
         'seven' => [ 
          'eight' => 'nine' 
         ] 
        ] 
       ] 
      ]; 

      # My key 
      $key = 'three.four.five'; 
      $keys = explode('.', $key); 
      $str = ""; 
      foreach ($keys as $k) { 
       $sq = "'"; 
       if (is_numeric($k)) { 
        $sq = ""; 
       } 
       $str .= "[" . $sq . $k . $sq . "]"; 
      } 
      $cmd = "unset(\$Data{$str});"; 
      eval($cmd); // <- i'd like to get rid of this evil shit 

對這個更漂亮的解決方案的任何想法?

回答

1

您可以使用對數組內部元素的引用,然後刪除$keys數組的最後一個鍵。

您應該添加一些錯誤處理/檢查是否實際存在的按鍵,但這是基礎:

$Data = [ 
      'one', 
      'two', 
      'three' => [ 
       'four' => [ 
        'five' => 'six', // <- I want to remove this one 
        'seven' => [ 
         'eight' => 'nine' 
        ] 
       ] 
      ] 
]; 

# My key 
$key = 'three.four.five'; 
$keys = explode('.', $key); 

$arr = &$Data; 
while (count($keys)) { 
    # Get a reference to the inner element 
    $arr = &$arr[array_shift($keys)]; 

    # Remove the most inner key 
    if (count($keys) === 1) { 
     unset($arr[$keys[0]]); 
     break; 
    } 
} 

var_dump($Data); 

A working example

+0

謝謝,這工作得很好:) – Link

1

您可以使用references來完成此操作。需要注意的是,你不能取消設置變量,但你可以使用unset a array key

一種解決方案是將下面的代碼

# My key 
$key = 'three.four.five'; 
$keys = explode('.', $key); 
// No change above here 


// create a reference to the $Data variable 
$currentLevel =& $Data; 
$i = 1; 
foreach ($keys as $k) { 
    if (isset($currentLevel[$k])) { 
     // Stop at the parent of the specified key, otherwise unset by reference does not work 
     if ($i >= count($keys)) { 
      unset($currentLevel[$k]); 
     } 
     else { 
      // As long as the parent of the specified key was not reached, change the level of the array 
      $currentLevel =& $currentLevel[$k]; 
     } 
    } 
    $i++; 
} 
+0

作品,謝謝:) – Link