PHP var_dump和循环给出不同的结果 [英] PHP var_dump and loop giving different results
问题描述
var_dump($ cursor);
foreach($ cursor为$ obj){
echo< div class ='item'id ='。 $ obj ['_ id']。 >中;
echo< span class ='listnick'> 。 $ obj ['nick']。 < /跨度> 中;
回显< / div>;
code $
var_dump的结果如下:
array(2){
[0] =>
& array(9){
[_id] =>
object(MongoId)#9(1){
[$ id] =>
string(24)50af8dcd9cc231534400000c
}
[nick] =>
string(6)safari
}
[1] =>
array(9){
[_id] =>
object(MongoId)#8(1){
[$ id] =>
string(24)50af8dca9cc2315644000009
}
[nick] =>
string(6)chrome
}
}
所以显然这个foreach应该打印出safari和chrome,但是这个问题真的很奇怪:
有时它会返回两次Safari并且省略chrome反之亦然。我试着把var_dump和foreach循环放在附近,以确保它们是相同的,并且两个命令之间的对象没有变化,但是我真的不知道发生了什么。
有什么帮助?提前感谢。
解决方案 注意safari是如何引用数组的:& array。 b
这可能是由于有一个foreach,其中$ obj是一个引用:
foreach($ cursor as& $ obj){
..
}
// unset($ obj);
在PHP中,$ obj的作用域并不以循环的执行结束,因此您应该
这也可能是因为在某处使用了引用赋值:
$ cursor [] =& $野生动物园;
I have the following code:
var_dump($cursor);
foreach($cursor as $obj) {
echo "<div class='item' id='" . $obj['_id'] . "'>";
echo "<span class='listnick'>" . $obj['nick'] . "</span>";
echo "</div>";
}
The result of var_dump is the following:
array(2) {
[0]=>
&array(9) {
["_id"]=>
object(MongoId)#9 (1) {
["$id"]=>
string(24) "50af8dcd9cc231534400000c"
}
["nick"]=>
string(6) "safari"
}
[1]=>
array(9) {
["_id"]=>
object(MongoId)#8 (1) {
["$id"]=>
string(24) "50af8dca9cc2315644000009"
}
["nick"]=>
string(6) "chrome"
}
}
so obviously the foreach should print out "safari" and "chrome", but the problem is really weird:
Sometimes it returns "safari" twice and omits "chrome", and viceversa for the other client. I tried putting the var_dump and the foreach loop near to be sure they are the SAME and there are no changes in the object between the two commands, but really I got no idea what's going on.
Any help? Thanks in advance.
解决方案 Notice how safari is a reference to an array: &array.
This might result from having a foreach where $obj is a reference:
foreach($cursor as &$obj) {
..
}
//unset($obj);
In PHP, the scope of $obj does not end with execution of the loop, so you should do an unset whenever you looped using a reference.
This might also result from using the reference assignment somewhere:
$cursor[] =& $safari;
这篇关于PHP var_dump和循环给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!