PHP Dynamic access to associative array
CHANGE FROM THE ORIGINAL THAT MEANED ONLY 1 ACCESS
If I have an array containing x number of arrays, each of the forms
array('country' => array('city' => array('postcode' => value)))
and another array which can be
array('country', 'city', 'postcode') or array('country', 'city')
depending on what i need to get how to use the second array to identify the index levels in the first array and then get it.
source to share
Okay, I apologize for not stating my question more clearly, initially, but I got it to hopefully, with a variable variable, like this:
$keystring = '';
foreach ($keys as $key) {
$keystring .= "['$key']";
}
Then move the main array for each of the country records in it and access the required value as:
eval('$value = $entry' . "$keystring;");
source to share
The nested links with $cur = &$cur[$v];
you can read and change 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']
source to share
Loop through the index array, traversing 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;
source to share