【问题标题】:PHP Array Not Working in FunctionPHP数组在函数中不起作用
【发布时间】:2011-05-30 12:57:07
【问题描述】:

我目前正在用 PHP 中的数组进行试验,并创建了一个假环境来显示团队的信息。

    $t1 = array (
            "basicInfo" => array (
                "The Sineps",
                "December 25, 2010",
                "lemonpole"
            ),
            "overallRecord" => array (0, 0, 0, 0),
            "overallSeasons" => array (
                1 => array (14, 0, 0),
                2 => array (9, 5, 2),
                3 => array (12, 4, 0),
                4 => array (3, 11, 2)
            ),
            "games" => array (
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />",
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />",
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />",
                "<img src=\"images/cs.gif\" alt=\"Counter-Strike\" />"
            ),
            "seasonHistory" => array (
                "Season I",
                "Season II",
                "Season III",
                "Season IV"
            ),
            "divisions" => array (
                "Open",
                "Main",
                "Main",
                "Invite"
            )
        );
// Displays the seasons the team has been in along
    // with the record of each season.
    function seasonHistory() {
        // Make array variable local-scope.
        global $t1;

        // Count the number of seasons.
        $numrows = count($t1["seasonHistory"]);

        // Loop through all the variables until
        // it reaches the last entry made and display
        // each item seperately.
        for($v = 0; $v <= $numrows; $v++) {
            // Echo each season.
            echo "<tr><td>{$t1["games"][$v]}</td>";
            echo "<td>{$t1["seasonHistory"][$v]}</td>";
            echo "<td>{$t1["divisions"][$v]}</td></tr>";
        }
    }

我已经测试了几个可能的问题,在缩小范围后我得出了一个结论,那就是我的函数由于某种原因没有连接到数组。我不知道还能做什么,因为我认为使数组全局化可以解决这个问题。

什么有效:

  1. 我可以在我需要它显示的页面上回显 $t1["games"][0],它会为我提供内容。

  2. 我尝试了 echo $t1["games"][0] INSIDE 函数,然后调用该函数,它没有显示任何内容。

【问题讨论】:

    标签: php arrays user-defined-functions


    【解决方案1】:
    extract($t1);
    

    试试这个函数而不是全局函数。

    更好的办法是将数组作为参数传递...

    function seasonHistory($array){
    
    $t1 = $array;
    
    //your function
    }
    

    【讨论】:

    • nope :( 它给了我一个错误,说参数需要一个数组。我猜这个错误是因为我的函数没有连接到数组...
    • 是的 :D 有效。我不明白为什么如果我一直在试验数组并简单地使数组全局始终有效,它为什么突然不起作用..
    • 尝试将数组作为参数传递,这应该可以正常工作。很奇怪 global 和 extract 不起作用。这是原码吗?
    • 是的,我自己制作了数组和函数。它以前在另一个环境中工作过。但是文件结构不同;然后我没有使用包含和开关。会是这样吗?
    • 好的,就是这样:) 通常以这种方式使用全局和提取是不好的,更好的解决方案是传递变量/数组之类的函数参数。请采纳为正确答案。
    【解决方案2】:

    如果您将$t1 定义不在全局范围内,则可能会发生这种情况。尝试在定义变量后立即执行 $GLOBALS['t1'] = $t1; 将其显式放入全局变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多