php 如何在 symfony2 控制器中迭代 ArrayCollection
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25668006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how iterate ArrayCollection in symfony2 Controller
提问by mohsenJsh
I want to iterate ArrayCollection
instance in Symfony2 Controller, What is the easiest way?
我想ArrayCollection
在 Symfony2 控制器中迭代实例,最简单的方法是什么?
edit:
编辑:
I thought it would work like normal array in php but I got error on this code:
我认为它会像 php 中的普通数组一样工作,但我在这段代码中遇到了错误:
foreach ($arrayCollectionInc as $Inc) {
}
采纳答案by iswinky
Simplest way:
最简单的方法:
$arr = $arrayCollectionInc->toArray();
foreach ($arr as $Inc) {
}
Working example:
工作示例:
$a = new ArrayCollection();
$a->add("value1");
$a->add("value2");
$arr = $a->toArray();
foreach ($arr as $a => $value) {
echo $a . " : " . $value . "<br />";
}
Result:
结果:
0 : value1
1 : value2
回答by Chip Dean
To those who find this question in the future there is another way that I would consider to be a better practice than the accepted answer, which just converts the ArrayCollection
to an array. If you are going to just convert to an array why bother with the ArrayCollection
in the first place?
对于那些将来发现这个问题的人,我认为还有另一种方法比接受的答案更好,后者只是将 转换ArrayCollection
为数组。如果您只想转换为数组,为什么ArrayCollection
首先要费心呢?
You can easily loop over an ArrayCollection
without converting it to an array by using the getIterator()
function.
您可以轻松地循环遍历 anArrayCollection
而无需使用该getIterator()
函数将其转换为数组。
foreach($arrayCollection->getIterator() as $i => $item) {
//do things with $item
}
回答by user1032531
Definitely agree one shouldn't convert to an array, however, ->getIterator()
isn't necessary.
绝对同意不应转换为数组,但是,->getIterator()
没有必要。
foreach($arrayCollection as $i => $item) {
//do things with $item
}