Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access php multidimensional array key based on a variable string

Tags:

arrays

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!

like image 897
ggirtsou Avatar asked Mar 17 '26 07:03

ggirtsou


2 Answers

I'm really glad that your goal is to stop using eval(). :-)

If I've understood you correctly, you have an array of $items and you're trying to locate things in it based on the contents of $xml_path.

I obviously haven't tested this on your data, but what about something like this?

<?php

$xml_path = 'response->items->item';

$explode_path = explode('->', $xml_path);

foreach($items as $item) {
  $step = $item;
  foreach($explode_path as $path) {
    $step = $step[$path];
  }
  echo $step . '<br />';
}

The idea is that for each of the $items, you step through the exploded path, narrowing your search as you go by refining $step perhaps to some unknown depth.

This of course assumes that for any value of $xml_path, there WILL be a corresponding item set in the $items array. Otherwise, you'll want to add some error handling. (You probably want error handling anyway.)

like image 89
ghoti Avatar answered Mar 18 '26 22:03

ghoti


$xml_tag = 'title';
$xml_path = 'response->items->item';

$explode_path = explode('->', $xml_path);

$items = $xml2array[$explode_path[0]][$explode_path[1]][$explode_path[2]];

foreach($items as $item) {
    echo $item[$xml_tag].'<br />';
}
like image 34
safrazik Avatar answered Mar 18 '26 22:03

safrazik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!