問題描述
我有一個對象數(shù)組.對象主要有一堆屬性,因為這些是元數(shù)據(jù)對象.
I have an array of objects. The objects mainly have a bunch of properties because these are meta-data objects.
所以就像$objects[]
就像一堆具有以下屬性的項目:object->item1
、object->item2
等
so it is like
$objects[]
is like a bunch of items that have properties like:
object->item1
, object->item2
, etc.
我想為每個對象添加一些東西,所以...
I want to add something to each of these objects, so...
foreach ($objects as &$object) {
$object->newItem=(something I compute);
}
然后,我想將這些對象顯示為 html 中的列表.所以,我去:
then later, I want to display these objects as a list in html. So, I go:
foreach ($objects as $object) {
<li><?php object output stuff here ?></li>
}
好的.現(xiàn)在,它工作正常,除了最后一個對象被丟棄并且倒數(shù)第二個對象顯示兩次.跆拳道??
ok. Now, it works fine, except the last object is discarded and the second to last object is displayed twice. WTF??
這對你有意義嗎?
推薦答案
如果你通過引用迭代,之后總是取消設置迭代變量:
If you iterate by reference, always unset the iteration variable afterwards:
foreach ($objects as &$object) {
// some code
}
unset($object);
摘自 foreach
文檔:
Excerpt from the foreach
documentation:
即使在 foreach 循環(huán)之后,對 $value 和最后一個數(shù)組元素的引用仍然存在.建議用unset()銷毀.
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
如果您想了解為什么您的代碼的行為方式如此,這里有一些進一步的閱讀:引用和foreach
If you want to understand why your code behaves the way it behaves, here is some further reading: References and foreach
這篇關于PHP foreach by reference 在遍歷對象數(shù)組時會導致奇怪的故障的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!