开发者

Finding a value inside a nested array having only a string with the keys

I have one array that contains some settings that looks like basically like this:

$defaults = array(
   'variable' => 'value', 
   'thearray' => array(
                  'foo' => 'bar'
                  'myvar' => array('morevars' => 'morevalues');
                  );
);

On another file, i get a string with the first level key and it's childs to check if there is a value attached to it. Using the array above, i'd get something like this:

$option = "thearray['myvar']['morevars']";

I need to keep this string with a similar format to the above because I also need to pass it to another function that saves to a database and having it in an array's format comes in handy.

My question is, h开发者_如何学运维aving the array and the string above, how can i check for both, existance and value of the given key inside the array? array_key_exists doesn't seem to work below the first level.


You could use a simple function to parse your key-string and examine the array like:

function array_deep_exists($array, $key)
{
    $keys = preg_split("/'\\]|\\['/", $key, NULL, PREG_SPLIT_NO_EMPTY);
    foreach ($keys as $key)
    {
        if ( ! array_key_exists($key, $array))
        {
            return false;
        }
        $array = $array[$key];
    }

    return true;
}

// Example usage
$defaults = array(
    'variable' => 'value', 
    'thearray' => array(
        'foo' => 'bar',
        'myvar' => array('morevars' => 'morevalues')
    )
);
$option = "thearray['myvar']['morevars']";
$exists = array_deep_exists($defaults, $option);
var_dump($exists);  // bool(true)

Finally, to get the value (if it exists) return $array where the above returns true.

Note that if your array might contain false, then when returning the value you'll have to be careful to differentiate no-matching-value from a successful false value.


You need to eval this code, and use isset function in an eval string, and don't forget to add $ character in right place before code eval

example:

eval("echo isset(\$defaults['varname']['varname2']);")

this will echo 0 or 1 (false or true) You can do anything in eval, like a php source

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜