Hunter J. Hunter J. - 1 year ago 57
PHP Question

PHP: Convert a standard array into associate array keys?

I'm working on a function that takes an array as a parameter, and then calls the value of a different associative array using the input array as keys. So for example,

array('level_1', 'level_2', 'level_3')

should become


I have a way to do this that I think will work, but it feels hacky and weird and I don't really want to use
unless I absolutely must.

function fetch($keys) {
if (!is_array($keys)) { $variable = array($keys); }
foreach ($keys as $key) {
$assoc_string .= '[' . str_replace('\'' . '\\\'' . $key) . ']';
$reqstring = 'if (isset($this->vars' . $assoc_string . ')) { return $this->vars' . $assoc_string . '; } else { return false; }';

That just doesn't seem right, does it? How could I convert a list of keys into an associative array?

Answer Source

How about something like this:

function fetch($keys) {
    if (!is_array($keys))
        $keys = array($keys);

    $arr = $this->vars;

    foreach($keys as $key)
        if (!isset($arr[$key]))
            return FALSE;

        $arr = $arr[$key];

    return $arr;