我正在尝试在对象类中编写 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/