Search code examples
phpassociative-arrayvariable-variables

PHP Dynamically accessing an associative array


EDITED FROM ORIGINAL THAT HAD IMPLIED ONLY 1 ACCESS

If I have an array that contains x number of arrays, each of the form

array('country' => array('city' => array('postcode' => value)))

and another array that might be

array('country', 'city', 'postcode') or array('country', 'city') 

depending on what I need to retrieve, how do I use the second array to identify the index levels into the first array and then access it.


Solution

  • Ok, I apologize for not having expressed my question more clearly, originally, but I got it to work as I was hoping, with a variable variable, as follows:

    $keystring = '';
    foreach ($keys as $key) {
      $keystring .= "['$key']";
    }
    

    Then iterate the main array, for each of the country entries in it, and access the desired value as:

    eval('$value = $entry' . "$keystring;");