我正在尝试在object类中编写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\ collection_objects \Collection,如何获得collection_objects属性数组
发布于 2015-11-10 11:01:42
\Doctrine\Common\Collections\Collection是一个也提供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()
];
}https://stackoverflow.com/questions/33627413
复制相似问题