dongnunai3125 2012-05-05 03:53
浏览 101
已采纳

使用php(需要避免eval)使用动态生成的变量访问多维数组键

I need to avoid eval() again. I want to access a multidimensional array like this:

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

The thing is that $explode_path[0] and $explode_path[1] are calculated through a for loop:

for($i=0; $i<$count_explode; $i++) { }

Right now the entire code looks like this:

function getValues($contents, $xml_path) {
    $explode_path = explode('->', $xml_path);
    $count_explode = count($explode_path);
    $xml2array = xml2array($contents);

    $correct_string = '$items = $xml2array';

    for($i=0; $i<$count_explode; $i++) {
        $correct_string .= '[$explode_path['.$i.']]';
    }

    $correct_string .= ';';
    eval($correct_string);
    return $items;
}

$contents = readfile_chunked($feed_url, true);
$items = getValues($contents, 'deals->deal'); # will get deals->deal from MySQL

foreach($items as $item) {
    echo $item['deal_title']['value'].' - '.$item['dealsite']['value'].'<br />';
}

I can't figure out how I can access the $xml2array array that way:

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

Any help would be highly appreciated!

  • 写回答

1条回答 默认 最新

  • duansao6776 2012-05-05 04:05
    关注

    What about replacing your getValues() function with:

    function getValues($contents, $xml_path) {
        $explode_path = explode('->', $xml_path);
        $count_explode = count($explode_path);
        $items = xml2array($contents);
    
        for($i=0; $i<$count_explode; $i++) {
            $items = $items[$explode_path[$i]];
        }
    
        return $items;
    }
    

    Edit: Cleaner version:

    function getValues($contents, $xml_path) {
        $items = xml2array($contents);
    
        foreach(explode('->', $xml_path) as $k)
        {
            $items = $items[$k];
        }
    
        return $items;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持