3

I am trying to write toArray() method in object class. This is class

Collection

   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' => [

            ]
    ];
}
}

How do I get array of collection_objects properties, if type of collection_objects is \Doctrine\Common\Collections\Collection

1 Answer 1

3

\Doctrine\Common\Collections\Collection is an interface that also provides a toArray() method. You'll be able to use that method directly on your collection:

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

There is one problem though. The array returned by \Doctrine\Common\Collections\Collection::toArray() is an array of \MyMini\CollectionBundle\Entity\CollectionObject objects and not an array of plain arrays. If your \MyMini\CollectionBundle\Entity\CollectionObject also facilitates a toArray() method you can use that to convert these to arrays as well like that for example:

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()
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.