Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how iterate ArrayCollection in symfony2 Controller

I want to iterate ArrayCollection instance in Symfony2 Controller, What is the easiest way?

edit:

I thought it would work like normal array in php but I got error on this code:

foreach ($arrayCollectionInc as $Inc) {

}
like image 423
mohsenJsh Avatar asked Sep 04 '14 14:09

mohsenJsh


3 Answers

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?

You can easily loop over an ArrayCollection without converting it to an array by using the getIterator() function.

foreach($arrayCollection->getIterator() as $i => $item) {
    //do things with $item
}
like image 81
Chip Dean Avatar answered Oct 25 '22 02:10

Chip Dean


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
like image 33
iswinky Avatar answered Oct 25 '22 00:10

iswinky


Definitely agree one shouldn't convert to an array, however, ->getIterator() isn't necessary.

foreach($arrayCollection as $i => $item) {
    //do things with $item
}
like image 24
user1032531 Avatar answered Oct 25 '22 02:10

user1032531