Symfony 2 Doctrine 导出到 JSON
我正在使用 Symfony 2 和 Doctrine 2 为 iOS 应用程序创建 Web 服务 (JSON).
I'm using Symfony 2 with Doctrine 2 to create a web service(JSON) for an iOS app.
要获取我的实体,我会这样做:
To fetch my entity i do:
$articles = $this->getDoctrine()->getRepository('UdoPaddujourBundle:MenuArticle')->findAll();
我必须告诉你:
$article = array();
$article = $articles->toArray();
给我以下错误:
Fatal error: Call to a member function toArray() on a non-object
同样的事情发生在
$article = $articles->exportTo('json');
<小时>
如何创建 json 响应?
How can i create a json response ?
亲切的问候,卡瑙丹
var_dump($articles) =
var_dump($articles) =
array(18) {
[0]=>
object(UdoPaddujourBundleEntityMenuArticle)#50 (4) {
["id":"UdoPaddujourBundleEntityMenuArticle":private]=>
int(1)
["name":"UdoPaddujourBundleEntityMenuArticle":private]=>
string(17) "My Article Name 1"
["description":"UdoPaddujourBundleEntityMenuArticle":private]=>
string(26) "My Article Description 1"
["price":"UdoPaddujourBundleEntityMenuArticle":private]=>
float(20)
}
[1]=> ...
- 稍后编辑
如何遍历所有属性名称"?这就是我所拥有的:
- LATER EDIT
How can i loop through all the "property names" ? This is what i've got:
$myarray=array();
$myArray["name"]=array();
$myArray["description"]=array();
foreach($articles in $article)
{
array_push($myArray["name"], $article->getName());
array_push($myArray["description"], $article->getDescription());
}
推荐答案
如果你使用学说查询,你也可以这样做:
If you use a doctrine query you can also do this:
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('SELECT ma FROM UdoPaddujourBundle:MenuArticle ma ...etc');
$myArray = $query->getArrayResult();
然后使用 json_encode($myArray);
参见 这里了解更多详情.
相关文章