1

Lets suppose I have this array:

$doc = array(
    'nfe' => array(
        'inf' => array(
            'det' => array(
                'emit' => array(
                     'name' => 'My name'
                )
            )
        )
    )
)

and another array with the keys I want to unset (in order):

$keys = ['nfe', 'inf', 'det', 'emit']

How can I dynamically do this:

unset($doc['nfe']['inf']['det']['emit']);

Based on both arrays $doc and $keys ?

Fantasmic
  • 1,122
  • 17
  • 25

1 Answers1

3

Playing around with some of my code from 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]);
}

Here is an eval method:

function unsetter($path, &$array) {
    $path = "['" . implode("']['", $path) . "']";
    eval("unset(\$array{$path});");
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87