基于变量字符串访问php多维数组键

ABC*_*ABC 2 php arrays

我已经将XML路径存储到字符串中的项目,如下所示:response->items->item.

我需要做的是访问一个名为$ xml_array的数组,如下所示:

$ xml_array [ '响应'] [ '项目'] [ '项目']

当我在代码中写它时,它工作.问题是我希望它能够在飞行中完成.

我用它来转换response->items->item['response']['items']['item']:

$xml_path = 'response->items->item';
$explode_path = explode('->', $xml_path);
$correct_string = false;

foreach($explode_path as $path) {
   $correct_string .= '[\''.$path.'\']';
}
Run Code Online (Sandbox Code Playgroud)

问题是我无法$xml_array通过这样做访问:$xml_array[$correct_string]

所以我最终得到了这个:

$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 />';
}
Run Code Online (Sandbox Code Playgroud)

$xml_array通过$items数组访问数组.有什么方法可以做到这一点并避免使用eval()?

提前致谢!

gho*_*oti 6

我很高兴您的目标是停止使用eval().:-)

如果我已经正确地理解了你,那么你有一个阵列,$items并且你正在尝试根据内容找到它$xml_path.

我显然没有在你的数据上测试过这个,但这样的事情怎么样?

<?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 />';
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是,对于每个$项目,您都会逐步完成分解路径,通过精炼$step到某个未知深度来缩小搜索范围.

这当然假设对于$ xml_path的任何值,$ items数组中都会有相应的项集.否则,您将需要添加一些错误处理.(你可能还需要错误处理.)