php – Symfony 2 Doctrine导出到JSON

前端之家收集整理的这篇文章主要介绍了php – Symfony 2 Doctrine导出到JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Symfony 2和Doctrine 2为iOS应用程序创建Web服务( JSON).

获取我的实体我做:

  1. $articles = $this->getDoctrine()->getRepository('UdoPaddujourBundle:MenuArticle')->findAll();

我必须告诉你:

  1. $article = array();
  2. $article = $articles->toArray();

给我以下错误

  1. Fatal error: Call to a member function toArray() on a non-object

同样的事情发生了

  1. $article = $articles->exportTo('json');

我怎样才能创建一个json响应?

亲切的问候,
Cearnau Dan

编辑:
var_dump($articles)=

  1. array(18) {
  2. [0]=>
  3. object(Udo\PaddujourBundle\Entity\MenuArticle)#50 (4) {
  4. ["id":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
  5. int(1)
  6. ["name":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
  7. string(17) "My Article Name 1"
  8. ["description":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
  9. string(26) "My Article Description 1"
  10. ["price":"Udo\PaddujourBundle\Entity\MenuArticle":private]=>
  11. float(20)
  12. }
  13. [1]=> ...

– 稍后编辑

我怎样才能遍历所有“属性名称”?
这就是我所拥有的:

  1. $myarray=array();
  2. $myArray["name"]=array();
  3. $myArray["description"]=array();
  4. foreach($articles in $article)
  5. {
  6. array_push($myArray["name"],$article->getName());
  7. array_push($myArray["description"],$article->getDescription());
  8. }
如果您使用学说查询,您也可以这样做:
  1. $em = $this->getDoctrine()->getEntityManager();
  2. $query = $em->createQuery('SELECT ma FROM UdoPaddujourBundle:MenuArticle ma ...etc');
  3. $myArray = $query->getArrayResult();

然后是json_encode($myArray);有关详细信息,请参见here

猜你在找的PHP相关文章