I have a array $a and some key arrays e.g. $keys1, $keys2,....
$a = array('a'=>array('b'=>array('c'=>array('d'=>123,'s'=>4),'r'=>3),'q'=>2),'p'=>1);
$keys1 = array('a','b','c');
$keys2 = array('a','b');
$a = Array
(
[a] => Array
(
[b] => Array
(
[c] => Array
(
[d] => 123
[s] => 4
)
[r] => 3
)
[q] => 2
)
[p] => 1
)
whenever $keys1 is used, output should be
Array
(
[d] => 123
[s] => 4
)
or whenever $keys2 is used, output should be
Array
(
[c] => Array
(
[d] => 123
[s] => 4
)
)
this is very simple I can achieve result by using $a[a][b][c]
in first case and by using $a[a][b]
in second case
Problem: these $keys are provided in form of array at run time, Is there any function in php to get the result?
Try this.
Comments are in code.
It will loop through the keys and return the searched value.
$a = array('a'=>array('b'=>array('c'=>array('d'=>123,'s'=>4),'r'=>3),'q'=>2),'p'=>1);
$keys1 = array('a','b','c');
$keys2 = array('a','b');
$keys = $keys1; // set this as "search value"
$value = $a; // create a copy of original array. Maybe not needed?
Foreach($keys as $key){ // loop keys in search value
$value = $value[$key]; // overwrite $value with subarray of $value[$key]
}
Var_dump($value); // dump the search return.