假设我有这个数组:
$doc = array(
'nfe' => array(
'inf' => array(
'det' => array(
'emit' => array(
'name' => 'My name'
)
)
)
)
)
和另一个我想取消设置的键的数组(按顺序):
$keys = ['nfe', 'inf', 'det', 'emit']
我该如何动态地做到这一点:
unset($doc['nfe']['inf']['det']['emit']);
基于两个数组$doc
和$keys
吗?
答案 0 :(得分:2)
试玩How to access and manipulate multi-dimensional array by key names / path?中的一些代码:
function unsetter($path, &$array) {
$temp =& $array;
$last = array_pop($path);
foreach($path as $key) {
$temp =& $temp[$key];
}
unset($temp[$last]);
}
这是一种eval
方法:
function unsetter($path, &$array) {
$path = "['" . implode("']['", $path) . "']";
eval("unset(\$array{$path});");
}