Jeff Greenberg
Jeff Greenberg

Reputation: 57

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.

Upvotes: 3

Views: 1408

Answers (3)

Jeff Greenberg
Jeff Greenberg

Reputation: 57

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;");

Upvotes: 0

Glen
Glen

Reputation: 889

Loop through the array of indexes, traveling down the initial array step by step until you reach the end of the index array.

$array1 = array('x' => array('y' => array('z' => 20)));
$keys = array('x', 'y', 'z');
$array_data = &$array1;
foreach($keys as $key){
    $array_data = &$array_data[$key];
}
echo $array_data;

Upvotes: 1

dynamic
dynamic

Reputation: 48091

By nesting references with $cur = &$cur[$v]; you can read and modify the original value:
Live example on ide1: http://ideone.com/xtmrr8

$array = array('x' => array('y' => array('z' => 20)));
$keys = array('x', 'y', 'z');

// Start nesting new keys
$cur = &$array;
foreach($keys as $v){
    $cur = &$cur[$v];
}

echo $cur;  // prints 20
$cur = 30;  // modify $array['x']['y']['z']

Upvotes: 1

Related Questions