问题描述:

I know that eval() is a horrible thing to use, but I couldn't think of a better way to do this.

I have the following method which I want to use to delete items from a multidimensional array, and it should delete the item if it exists.

public function delete(){

$keys = func_get_args();

$str = "";

foreach($keys as $key){

$str .= "['$key']";

}

eval("if(isset(\$_SESSION$str)){unset(\$_SESSION$str);}");

}

To use it I would make a call like so:

$obj->delete("one", "two", "three");

which would be the equivalent to this:

if(isset($_SESSION["one"]["two"]["three"])){

unset($_SESSION["one"]["two"]["three"]);

}

Is there a better way to do this than using eval()?

网友答案:

This will achieve what you want:

function delete(){
    $keys = func_get_args();

    $ref = &$_SESSION;
    for($x = 0; $x < sizeOf($keys)-1; $x++) {
        $ref = &$ref[$keys[$x]];
    }
    unset($ref[$keys[sizeOf($keys)-1]]);
    unset($ref);
}
网友答案:

There is a function like that in Ouzo Goodies:

Arrays::removeNestedKey($_SESSION, ['one', 'two', 'three']);

If you don't want to include the lib, you can take a look at the source code and grab the function itself:

public static function removeNestedKey(array &$array, array $keys)
{
    $key = array_shift($keys);
    if (count($keys) == 0) {
        unset($array[$key]);
    } else {
        self::removeNestedKey($array[$key], $keys);
    }
}
相关阅读:
Top