Basically, if I had a DoctrineCollection of DoctrineRecord objects, and wanted to convert it to an array, I could use:
$collection->toArray()
or $collection->getData()
But I don't understand what's the difference between this two methods.
Just an update for Doctrine 2:
->getData()
has become
->getValues()
Gonzalo was right for Doctrine 1, but hopefully this helps anyone who also found this thread looking for an answer but encountered problems using getData().
(Sorry Gonzalo, I don't have the reputation score yet to comment.)
Update: See response below for Doctrine 2. This response only covers Doctrine 1
->toArray()
Most programmers would probably assume that calling toArray() on the collection would simply place all the objects into an array. While toArray() does do that, it also converts the objects themselves into associative arrays, which is likely not what you want.
toArray()
is equivalent to this
$q = Doctrine_Query::create()
->from('Post p')
->setHydrationMode(Doctrine::HYDRATE_ARRAY);
$resultSet = $q->execute(); // $resultSet is an array
according to the documentation
foreach ($resultSet as $post) {
// $post is an array
echo $post['title'];
}
so each element of the array is also an array associative.
Instead:
->getData()
Not exactly the most intuitive name, getData() actually takes all the objects in the Doctrine Collection object and places them into an array – without altering the objects themselves.
so you will get objects!
foreach ($resultSet as $post) {
// $post is not an array
echo $post->Id;
}
source: here
Keep in mind this only works for Doctrine 1, for Doctrine 2 see answer below (or comments)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With