2017-09-20 52 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