如何在php中使用变量指定数组?

时间:2012-02-22 12:06:35

标签: php arrays variables key

我需要帮助我如何使用变量指定数组名称或键? 我已经尝试了无数次但它永远不会起作用

在我进入代码之前,$ games是数组,我在底部显示

这是我的代码(我将在底部显示数组示例)

$increment = 0; //increment i use in a while loop +1 per loop starting at 0
$increment2 = increment - 1; // to get the game number i need to minus 1 from $increment, 
//this works since the array starts at 0 and increment will be 1 when the while loop  starts.

$gamestotal = $games[totalGames]; //This number is different everytime, it is always 
//between 1-1000, it counts the number of a games a person has.
$gamesnpcommid = $games[$increment2][npcommid]; //each game has a unique code, i cURL this 
//info from Sony servers and return it in an array (array example below) This is the part 
//that is not working, to help understand please check array first, this variable is used   
//in the while loop and i need it to start at array 0 and keep returning the unique code
//until the loops stops at the final array number.

//这是循环

while($increment<$gamestotal)

    if($increment % 2 == 0){
    $increment=$increment+1;
        echo "<tr>";
        echo "<td style='background-color:#e6e8fa'>";
        echo $gamesnpcommid;
        echo "</td>";
        echo "</tr>";
    }
    else
    {$increment=$increment+1;
        echo "<tr>";
        echo "<td style='background-color:adeaea'>";
        echo $gamesnpcommid;
        echo "</td>";
        echo "</tr>";
    }

echo "</table>";

一切都工作得很好但是数组引用不起作用($gamesnpcommid),这里是数组$games的样子的例子:

数组存储在变量$games

Array
(
    [totalGames] => 110
    [0] => Array
        (
            [npcommid] => NPWR00507_00
            [platinum] => 0
            [gold] => 1
            [silver] => 11
            [bronze] => 32
            [total] => 44
            [lastupdated] => 1329258539
        )

    [1] => Array
        (
            [npcommid] => NPWR01140_00
            [platinum] => 1
            [gold] => 4
            [silver] => 8
            [bronze] => 29
            [total] => 42
            [lastupdated] => 1328586022
        )

    [2] => Array
        (
            [npcommid] => NPWR01118_00
            [platinum] => 0
            [gold] => 0
            [silver] => 3
            [bronze] => 8
            [total] => 11
            [lastupdated] => 1328067349
        )
    )

有人可以向我解释为什么,例如,$increment2 = 2 然后当我尝试使用$games[$increment2][npcommid]引用数组时,它不像数组一样返回NPWR01118_00? 但是当我使用$games[2][npcommid]时,它有效吗? 我已经完成了彻底的调试,我知道阵列工作正常,但此时我很难过。

2 个答案:

答案 0 :(得分:1)

您总是可以添加error_reporting(E_ALL);来了解您遇到的错误,现在正在同一个项目中工作

答案 1 :(得分:0)

尝试

$games[$increment2]["npcommid"] 

而不是

$games[$increment2][npcommid]
换句话说,总是必须引用关联键。