变量初始化中未定义的索引

时间:2012-08-29 09:11:52

标签: indexing undefined

$result2 = mysql_query($query, $con);
            while($data2 = mysql_fetch_assoc($result2))
            {
                $x = $data2["x"];
                $y = $data2["y"];
                echo "$x";
                echo "$y";
                if($x<0 && $y<0)
                {
                    echo "village: $data[village]  ";
                    echo "player: $data[player]  ";
                    echo "position: ($data[x]|$data[y])<br>";
                }
                else if($x>0 && $y>0)
                {
                    echo "village: $data[village]  ";
                    echo "player: $data[player]  ";
                    echo "position: ($data[x]|$data[y])<br>";
                }
                else if($x>0 && $y<0)
                {
                    echo "village: $data[village]  ";
                    echo "player: $data[player]  ";
                    echo "position: ($data[x]|$data[y])<br>";
                }
            }

我收到错误

Notice: Undefined index: y in C:\xampp\htdocs\debal\nw_check_exec.php on line 48

Notice: Undefined index: x in C:\xampp\htdocs\debal\nw_check_exec.php on line 47

第47行和第48行是: -

$x = $data2["x"];
$y = $data2["y"];

我认为我已经做好了所有事情,我无法弄清楚错误的原因。

1 个答案:

答案 0 :(得分:1)

$data2实际上没有索引x所以你需要检查它并使用instat默认值。

您可以使用小内联if语句:

$x = isset($data2["x"]) ? $data2["x"] : 0;
$y = isset($data2["y"]) ? $data2["y"] : 0;

那么你真的定义了这么多常量吗?例如。这里:

$data[village]

这意味着必须有一个常数village可能带有一些值“村庄”?

也许你应该用:

交换它
$data["village"]