PHP Doctrine : object toArray() method

标签 php symfony doctrine-orm doctrine

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

收藏

   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\Collections\Collection,我如何获取 collection_objects 属性数组

最佳答案

\Doctrine\Common\Collections\Collection 是一个接口(interface),它还提供了一个 toArray() 方法。您将能够直接在您的收藏中使用该方法:

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() 方法,您可以使用它来将它们转换为数组,例如:

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()
    ];
}

关于PHP Doctrine : object toArray() method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627413/

相关文章:

PHP : Search all record from array with specific value

symfony - 只是尝试安装/配置symfony2

php - symfony2 Controller 的功能测试 : How to generate a route

symfony - 是否有即将出版的 Symfony 2 书籍?

php - 使用外部 SQL 数据库使 Doctrine 实体保持最新

php - 如何在 Doctrine2/ZF2 中使用 Memcached?

php - 使用 sprintf 打印浮点值

php - 创建一个变量,该变量是两个其他变量的总和

php - 在 PHP 中防止目录遍历但允许路径

mysql - Symfony2 存储库和自定义连接