我可以看到我想看到的输出,但有两个我无法理解的错误:
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
?>
答案 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
(您尚未设置的那个)。
您有两个快速解决此问题的方法:
$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];