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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题