我有这样的阵列
$arr = [
'baz' => [
'foo' => [
'boo' => 'whatever'
]
]
];
Run Code Online (Sandbox Code Playgroud)
无论如何使用字符串输入取消设置['boo']值?
这样的事情
$str = 'baz->foo->boo';
function array_unset($str, $arr) {
// magic here
unset($arr['baz']['foo']['boo']);
return $arr;
}
Run Code Online (Sandbox Code Playgroud)
这个答案非常棒,它是我脚本运行的第一部分.使用字符串路径设置嵌套数组数据 .但它不能逆转.PS 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);
Run Code Online (Sandbox Code Playgroud)
本质上,您遍历数组树,但保留对要从中删除节点的最后一个数组(倒数第二个节点)的引用.然后调用unset最后一个数组,将最后一个节点作为键传递.