什么是“未定义偏移”?"试图获得非客体的属性"通知的意思


What do "undefined offset" and "trying to get property of non-object" notices mean?

我可以看到我想要看到的输出,但有两个错误,我不能理解:

 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
?>

$i=1在你的文件的顶部

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

答案

这两个通知都指的是同一个问题。您从索引1开始在$dasharr中分配索引,这在编程惯例上有点不寻常和不一致。然后你正在做一个向后的while循环测试while($numofdash > 0),并试图检索$dasharr[$numofdash-1],这将是$dasharr[0](你还没有设置的那个),当$numofdash = 1

你有两个快速解决这个问题的方法:

  • 将while循环设置为测试$numofdash > 1而不是
  • 让你的$dasharr0开始(建议)
其他调整

如果您打算遵循后者,您可以轻松地删除$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];

你有:$dasharr[$numofdash-1],如果$numofdash是1,那么你引用的是$dasharr[0],它不是在while循环中设置的。

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

$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的元素。

为了避免以后出现这样的问题,请使用var_dump()函数进行调试。