首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >:object toArray()方法

:object toArray()方法
EN

Stack Overflow用户
提问于 2015-11-10 10:04:39
回答 1查看 3K关注 0票数 3

我正在尝试在object类中编写toArray()方法。这是课

集合

代码语言:javascript
复制
   class Collection{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank()
 */
private $name;

/**
 * @ORM\OneToMany(targetEntity="MyMini\CollectionBundle\Entity\CollectionObject", mappedBy="collection", cascade={"all"})
 * @ORM\OrderBy({"date_added" = "desc"})
 */
private $collection_objects;

/*getter and setter*/

public function toArray()
     {
       return [
           'id' => $this->getId(),
           'name' => $this->name,
           'collection_objects' => [

            ]
    ];
}
}

如果collection_objects的类型为\Doctrine\Common\ collection_objects \Collection,如何获得collection_objects属性数组

EN

回答 1

Stack Overflow用户

发布于 2015-11-10 11:01:42

\Doctrine\Common\Collections\Collection是一个也提供toArray()方法的接口。您将能够在集合上直接使用该方法:

代码语言:javascript
复制
public function toArray()
{
    return [
        'id' => $this->getId(),
        'name' => $this->name,
        'collection_objects' => $this->collection_objects->toArray()
    ];
}

不过有一个问题。\Doctrine\Common\Collections\Collection::toArray()返回的数组是\MyMini\CollectionBundle\Entity\CollectionObject对象的数组,而不是普通数组的数组。如果您的\MyMini\CollectionBundle\Entity\CollectionObject还简化了toArray()方法,您可以使用它将这些转换为数组,例如:

代码语言:javascript
复制
public function toArray()
{
    return [
        'id' => $this->getId(),
        'name' => $this->name,
        'collection_objects' => $this->collection_objects->map(
            function(\MyMini\CollectionBundle\Entity\CollectionObject $o) {
                return $o->toArray();
            }
        )->toArray()
    ];
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33627413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档