PHP variable variable array key list
I have a multidimensional array where this works:
print_r( $temp[1][0] );
How can I make this work... I have the list of keys as a string like this:
$keys = "开发者_如何学编程[1][0]";
I want to access the array using the string list of keys, how can it be done? This works but the keys are obviously hard coded:
$keys = "[1][0]";
$tempName = 'temp';
print_r( ${$tempName}[1][0] );
// tried lots of variations like, but they all produce errors or don't access the array
print_r( ${$tempName.${$keys}} );
Thanks, Chris
function accessArray(array $array, $keys) {
if (!preg_match_all('~\[([^\]]+)\]~', $keys, $matches, PREG_PATTERN_ORDER)) {
throw new InvalidArgumentException;
}
$keys = $matches[1];
$current = $array;
foreach ($keys as $key) {
$current = $current[$key];
}
return $current;
}
echo accessArray(
array(
1 => array(
2 => 'foo'
)
),
'[1][2]'
); // echos 'foo'
Would be even nicer, if you passed in array(1, 2)
, instead of [1][2]
: One could avoid the (fragile) preg_match_all
parsing.
精彩评论