php – DoctrineCollection:toArray()和getData()之间的区别

基本上,如果我有一个DoctrineCollection的DoctrineRecord对象,并想将其转换为数组,我可以使用:

$collection-> toArray()或$collection-> getData()

但我不明白这两种方法之间的区别.

解决方法:

->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()等同于此

$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'];
}

所以数组的每个元素也是一个数组关联.

代替:

->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.

所以你会得到物品!

foreach ($resultSet as $post) {
        // $post is not an array
        echo $post->Id;
    }

来源:here

请记住,这仅适用于Doctrine 1,对于Doctrine 2,请参阅下面的答案(或评论)

相关文章

文章浏览阅读8.4k次,点赞8次,收藏7次。SourceCodester Onl...
文章浏览阅读3.4k次,点赞46次,收藏51次。本文为大家介绍在...
文章浏览阅读1.1k次。- php是最优秀, 最原生的模板语言, 替代...
文章浏览阅读1.1k次,点赞18次,收藏15次。整理K8s网络相关笔...
文章浏览阅读1.2k次,点赞22次,收藏19次。此网络模型提供了...
文章浏览阅读1.1k次,点赞14次,收藏19次。当我们谈论网络安...