duanqiao2006 2013-07-09 14:48
浏览 68
已采纳

为什么在尝试解析多维数组时会得到“未定义的变量”?

I'm trying to retrieve an item from a multi-dimensional array through a string that describes the path into the array (like first.second.third).

I've chosen the approach as shown here (also available on ideone):

<?php
    // The path into the array
    $GET_VARIABLE = "a.b.c";
    // Some example data
    $GLOBALS["a"]= array("b"=>array("c"=>"foo"));

    // Construct an accessor into the array
    $variablePath = explode( ".", $GET_VARIABLE );
    $accessor = implode( "' ][ '", $variablePath );
    $variable = "\$GLOBALS[ '". $accessor . "' ]";

    // Print the value for debugging purposes (this works fine)
    echo $GLOBALS["a"]["b"]["c"] . "
";
    // Try to evaluate the accessor (this will fail)
    echo $$variable;
?>

When I run the script, it will print two lines:

foo
PHP Notice:  Undefined variable: $GLOBALS[ 'a' ][ 'b' ][ 'c' ] in ...

So, why does this not evaluate properly?

  • 写回答

4条回答 默认 最新

  • duanao2688 2013-07-09 14:55
    关注

    I think the $$ notation only accepts a variable name (ie. the name of a variable). You are actually trying to read a variable named "$GLOBALS[ 'a' ][ 'b' ][ 'c' ]", which does not exist.

    As an alternative ($GET_VARIABLE seems to be your input string), you could try this:

    $path = explode('.', $GET_VARIABLE);
    echo $GLOBALS[$path[0]][$path[1]][path[2]];
    

    Wrap this in a suitable loop to make it more dynamic; it seems to be trivial.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?