什么"未定义的偏移"和"试图获得非对象的财产"通知是什么意思?

时间:2013-03-27 20:54:19

标签: php warnings

我可以看到我想看到的输出,但有两个我无法理解的错误:

 Notice: Undefined offset: 0 in C:\wamp\www\dash\handle_dashim.php on line 23
 Notice: Trying to get property of non-object in C:\wamp\www\dash\handle_dashim.php on line 23

代码的重要部分:

//move the objects into array.
$dasharr=array();
$i=1;
while(($row = mysql_fetch_array($dashim))) { 
    $dasharr[$i]=new dash($row["name"],$row["msg"],$row["msg_date"],$row["votes"]);
    $i++;
}

//checks the object with the most votes.
$numofdash=count($dasharr); 
$mostvotes=$dasharr[$numofdash];
while($numofdash>0){
    if(($mostvotes->votes)<($dasharr[$numofdash-1]->votes)){ //line 23
    $mostvotes=$dasharr[$numofdash-1];
    }
    $numofdash--;
}


echo $mostvotes->name; //I can see the output that I want

?>

4 个答案:

答案 0 :(得分:1)

$i=1位于文件顶部。

因此,您的第一行$dasharr[$i]$dasharr[1]及以上。因此,$dasharr[1-0]$dasharr[0]循环中的第一次将是未定义的。

答案 1 :(得分:0)

如果$dasharr[$numofdash-1]为1,您有$numofdash,那么您引用的$dasharr[0]在while循环中未设置。

答案 2 :(得分:0)

请从前6行代码中删除$i

$dasharr=array();
while(($row = mysql_fetch_array($dashim))) { 
    $dasharr[] = new dash($row["name"],$row["msg"],$row["msg_date"],$row["votes"]);
}

当所有数组索引从0开始并以1开头时,您的数组将成为关联数组。这意味着,您应该使用例如foreach语句来枚举它。

如果你有例如5行,你将拥有以下$ dasharr结构:

[1] => dash object,
[2] => dash object,
[3] => dash object,
[4] => dash object,
[5] => dash object

count($dasherr)等于5时,您的代码永远不会到达索引为5的元素,在您的情况下,您有一个错误请求索引为0的元素。< / p>

要在将来避免此类问题,请使用var_dump()函数进行调试。

答案 3 :(得分:0)

<强>答案

这两个通知都指的是同一个问题。您开始从索引$dasharr分配1中的索引,这在编程约定上有点不寻常且不一致。然后,您正在进行向后循环测试while($numofdash > 0)并尝试在$dasharr[$numofdash-1]时检索$dasharr[0] $numofdash = 1(您尚未设置的那个)。

您有两个快速解决此问题的方法:

  • 设置您的while循环以测试$numofdash > 1而不是
  • $dasharr(建议)
  • 开始0开始

其他调整

如果您打算遵循后者,可以通过以下方式轻松删除$i变量的使用:

$dasharr = array();
while(($row = mysql_fetch_array($dashim)))
    $dasharr[] = new dash($row["name"], $row["msg"], $row["msg_date"], $row["votes"]);

$a[] = ...符号将对象推送到数组中最近的空索引(自0开始)。

我还建议您在代码的最后一部分使用for循环代替while循环吗?

$mostvotes = $dasharr[$numofdash];
for ($numofdash = count($dasharr); $numofdash > 0; $numofdash--)
    if(($mostvotes->votes) < ($dasharr[$numofdash-1]->votes))
        $mostvotes = $dasharr[$numofdash-1];