Access php multidimensional array key based on a variable string
Posted
by
ggirtsou
on Stack Overflow
See other posts from Stack Overflow
or by ggirtsou
Published on 2012-03-27T05:12:02Z
Indexed on
2012/03/27
5:29 UTC
Read the original article
Hit count: 109
php
I have stored the XML path to items in a string like this: response->items->item
.
What I need to do is to access an array called $xml_array like this:
$xml_array['response']['items']['item']
When I write it in the code it works. The thing is that I want it to be done on the fly.
I use this to convert response->items->item
to ['response']['items']['item']
:
$xml_path = 'response->items->item';
$explode_path = explode('->', $xml_path);
$correct_string = false;
foreach($explode_path as $path) {
$correct_string .= '[\''.$path.'\']';
}
the problem is that I can't access $xml_array
by doing this: $xml_array[$correct_string]
So I end up with this:
$xml_tag = 'title';
$xml_path = 'response->items->item';
$correct_string = '$items = $xml2array';
$explode_path = explode('->', $xml_path);
foreach($explode_path as $path) {
$correct_string .= '[\''.$path.'\']';
}
$correct_string .= ';';
eval($correct_string);
foreach($items as $item) {
echo $item[$xml_tag].'<br />';
}
and access the $xml_array
array through $items
array. Is there any way I can do this and avoid using eval()?
Thanks in advance!
© Stack Overflow or respective owner