Reputation: 11
I have the following array:
$array1 = array("X", "Y", "Z")
The array values of $array1
are the keys of another array. And I want to access that element like this:
$array2["X"]["Y"]["Z"]
Any idea on how I would do this?
Upvotes: 0
Views: 174
Reputation: 4207
You can loop through with keys array, and check whether keys are present in source array, and keep storing them to a new array.
At last when keys loop finishes, you will left with result in your new array.
$array1 = array("X","Y","Z");
$array2 = array('X' => array('Y' => array('Z' => array('A' => 'B'))));
function getValue($keys, $source){
$ref = $source;
foreach($keys as $key) {
if(isset($ref[$key])) $ref = $ref[$key];
else return false;
}
return $ref;
}
print_r(getValue($array1, $array2));
Example: https://eval.in/571509
Upvotes: 0
Reputation: 59681
First off we will assign $array1
and $array2
to other variables, since we are going to modify and work with them. So in case you need the original arrays later on. We assign the first array, which are the keys of the second, to the variable $keys
. And the second array to $tmp
:
$keys = $array1;
$tmp = $array2;
Then we are going to loop over the keys with a while loop and always shift the first element down from the array with array_shift()
:
while($key = array_shift($keys)){
}
Means in my example it would be:
iteration 1: $key = A
iteration 2: $key = B
iteration 3: $key = C
As I said before we assign the second array to $tmp
. This means:
$array2 = ["A" => ["B" => ["C" => "RESULT"]]];
$tmp = $array2;
//$tmp = ["A" => ["B" => ["C" => "RESULT"]]];
Now we start the loop and check if $key
exists in our $tmp
variable. If it does we assign that element back to $tmp
and loop over the next key and do the same. If at any point the key does not exist we can break the loop.
Visualized:
iteration 1:
key = A
tmp = ["A" => ["B" => ["C" => "RESULT"]]]
tmp[A] = EXISTS TRUE
TRUE -> tmp = tmp[A] //tmp = ["B" => ["C" => "RESULT"]]
FALSE -> break
iteration 2:
key = B
tmp = ["B" => ["C" => "RESULT"]]
tmp[B] = EXISTS TRUE
TRUE -> tmp = tmp[B] //tmp = ["C" => "RESULT"]
FALSE -> break
iteration 3:
key = C
tmp = ["C" => "RESULT"]
tmp[C] = EXISTS TRUE
TRUE -> tmp = tmp[C] //tmp = "RESULT"
FALSE -> break
tmp = "RESULT"
Now at the end we of course have to check if all those keys existed and we got our result in $tmp
or not. We do this just by checking if $tmp
is not an array anymore and didn't got "stuck" somewhere by a key which wasn't found.
<?php
$array1 = ["A", "B", "C"];
$array2 = ["A" => ["B" => ["C" => "RESULT"]]];
$keys = $array1;
$tmp = $array2;
while($key = array_shift($keys)){
if(isset($tmp[$key]))
$tmp = $tmp[$key];
else
break;
}
if(!is_array($tmp))
echo $tmp;
else
echo "Element does not exist";
?>
Upvotes: 2