问题
I have the following:
$values = Array (
['level1'] => Array (
['level2'] => Array(
['level3'] => 'Value'
)
)
)
I also have an array of keys:
$keys = Array (
[0] => 'level1',
[1] => 'level2',
[2] => 'level3'
)
I want to be able to use the $keys array so I can come up with: $values['level1']['level2']['level3']. The number of levels and key names will change so I need a solution that will read my $keys array and then loop through $values until I get the end value.
回答1:
You could iterate over $values
and store a $ref
like this :
$ref = $values ;
foreach ($keys as $key) {
if (isset($ref[$key])) {
$ref = $ref[$key];
}
}
echo $ref ; // Value
You also could use references (&
) to avoid copy of arrays :
$ref = &$values ;
foreach ($keys as &$key) {
if (isset($ref[$key])) {
$ref = &$ref[$key];
}
}
echo $ref ;
回答2:
<?php
$values['level1']['level2']['level3'] = 'Value';
$keys = array (
0 => 'level1',
1 => 'level2',
2 => 'level3'
);
$vtemp = $values;
foreach ($keys as $key) {
try {
$vtemp = $vtemp[$key];
print_r($vtemp);
print("<br/>---<br/>");
}
catch (Exception $e) {
print("Exception $e");
}
}
Hope this helps. Of course remove the print
statements but I tried it and in the end it reaches the value. Until it reaches the values it keeps hitting arrays, one level deeper at a time.
来源:https://stackoverflow.com/questions/49074943/php-getting-value-of-nested-array-from-array-of-keys