如何动态取消设置嵌套数组键?

时间:2019-10-01 18:18:50

标签: php arrays unset

假设我有这个数组:

$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吗?

1 个答案:

答案 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});");
}