使用字符串路径从数组中删除元素


Using string path to delete element from array

我有一个这样的数组

$arr = [
   'baz' => [
      'foo' => [
         'boo' => 'whatever'
     ]
   ]
];

是否可以使用字符串输入来取消设置['boo']值?

类似的

    $str = 'baz->foo->boo';
    function array_unset($str, $arr) {
    // magic here
    unset($arr['baz']['foo']['boo']);
    return $arr;
    }

这个答案太棒了,它让我的脚本的第一部分使用字符串路径来设置嵌套的数组数据. 但它不能逆转。注:eval()不是一个选项:(

由于不能在引用的元素上调用unset,因此需要使用另一个技巧:

function array_unset($str, &$arr)
{
    $nodes = split("->", $str);
    $prevEl = NULL;
    $el = &$arr;
    foreach ($nodes as &$node)
    {
        $prevEl = &$el;
        $el = &$el[$node];
    }
    if ($prevEl !== NULL)
        unset($prevEl[$node]);
    return $arr;
}
$str = "baz->foo->boo";
array_unset($str, $arr);

实际上,您遍历数组树,但保留对最后一个数组(倒数第二个节点)的引用,您希望从中删除该节点。然后在最后一个数组上调用unset,将最后一个节点作为键传递。

查看此代码

这个和Wouter Huysentruit的很像。不同之处在于,如果传递一个无效的路径,它将返回null。

function array_unset(&$array, $path)
{
    $pieces = explode('.', $path);
    $i = 0;
    while($i < count($pieces)-1) {
        $piece = $pieces[$i];
        if (!is_array($array) || !array_key_exists($piece, $array)) {
            return null;
        }
        $array = &$array[$piece];
        $i++;
    }
    $piece = end($pieces);
    unset($array[$piece]);
    return $array;
}

一些可能对你有用的东西:

$str = 'bar,foo,boo';
function array_unset($str,&$arr) {
  $path = explode(',',$str);
  $buf = $arr;
  for($i=0;$i<count($path)-1;$i++) {
    $buf = &$buf[$path[$i]];
  }
  unset($buf);
}