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

时间:2012-05-05 03:53:54

标签: php multidimensional-array eval

我需要再次避免使用eval()。我想访问这样的多维数组:

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

问题是$ explode_path [0]和$ explode_path [1]是通过for循环计算的:

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

现在整个代码看起来像这样:

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 />';
}

我无法弄清楚如何以这种方式访问​​$ xml2array数组:

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

任何帮助都将受到高度赞赏!

1 个答案:

答案 0 :(得分:1)

如何用以下内容替换getValues()函数

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;
}

修改:清洁版:

function getValues($contents, $xml_path) {
    $items = xml2array($contents);

    foreach(explode('->', $xml_path) as $k)
    {
        $items = $items[$k];
    }

    return $items;
}