2

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

$variable_defined_within_function['level_1']['level_2']['level_3']

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 eval() 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; }';
  eval($reqstring);
}

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

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I once again neglected the power of foreach. Aside from some of your formatting issues, this worked! Thank you
1

Please consider this function as a starting point:

function fetch(array $keys, array $array) {
        $pointer = &$array;

        foreach ($keys as $key) {
            if (!isset($pointer[$key])) 
                break;

            $pointer = &$pointer[$key];
        }

        return $pointer;

    }

it will loop through $array with provided $keys and return the value of the last existing key. You can use it as a base and add your logic for keys that not exists or something

Comments

0

Here is the solution, very simple, but yet, still very confusing sometimes.

$arr = array('level_1', 'level_2', 'level_3'); 

function fetch(array $array){
    $numberOfDimensions = count($array);

    // the value of array['level_1']['level_2']['level_3']
    $value = "something";
    for($i = $numberOfDimensions-1; $i >= 0; $i--){
        $value = array($array[$i] => $value);
    }
    return $value;
}

print_r(fetch($arr));

Output:

Array ( [level_1] => Array ( [level_2] => Array ( [level_3] => something ))) 

As you can see, the solution is very simple, but to understand what is going on, you must understand how array works.

Every array has index, or hash when talking about associative arrays, and for each of those keys there is only exactly one value. The value can be of any type, so if we add an array as value of another array's element, you get 2-dimensional array. If you add 2-dimensional array as value of another arrays's element, you get 3-dimensional array. By repeating the process, you get N-dimensional array.

The algorithm works by going from the deepest key (the last element inside keys array) and assigning a new associative array to the $value variable, which is the value prepared to be set as array value of dimension above, all until the end of loop.

Lets have a look at the changes made to variable $value inside for loop, before and after change.

The initial value of variable $value is "something". "something" is value of array level_3, and so on...

So, running

print_r(array['level_1']['level_2']['level_3']);

will produce

something

Here is a full state view of the $value variable inside for loop:

Key: level_3

something
Array ( [level_3] => something )

Key: level_2

Array ( [level_3] => something )
Array ( [level_2] => Array ( [level_3] => something ) )

Key: level_1

Array ( [level_2] => Array ( [level_3] => something ) )
Array ( [level_1] => Array ( [level_2] => Array ( [level_3] => something ) ) ) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.