Heim >Backend-Entwicklung >PHP-Tutorial >symfony 使用 findall读取出来的数据 如何转成 json

symfony 使用 findall读取出来的数据 如何转成 json

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-20 12:43:041175Durchsuche

$repository = $this->getDoctrine()->getRepository('AppBundle:User');$all = $repository->findAll();


array (size=2)  0 =>     object(AppBundle\Entity\User)[248]      private 'id' => int 1      private 'name' => string 'A Foo Bar' (length=9)      private 'pass' => string '19.99' (length=5)  1 =>     object(AppBundle\Entity\User)[251]      private 'id' => int 2      private 'name' => string 'Two Fot Bar' (length=11)      private 'pass' => string '40.00' (length=5)


返回的数据是这样的, 现在这个 如何转成 json数据
我现在用 return new JsonResponse($all);   [{}]


回复讨论(解决方案)

你需要给 AppBundle\Entity\User 实现 JsonSerializable 接口

class T implements JsonSerializable {  private $id;  private $name;  private $pass;  function __construct($id, $name, $pass) {    $this->id = $id;    $this->name = $name;    $this->pass = $pass;  }  function jsonSerialize() {    return array(      'id' => $this->id,      'name' => $this->name,      'pass' => $this->pass,      );  }}$d[] = new T(1, 'a', 'p');$d[] = new T(2, 'b', 'p');echo json_encode($d);
[{"id":1,"name":"a","pass":"p"},{"id":2,"name":"b","pass":"p"}]
否则只能是 [{},{}]
因为返回的属性是私有的

你需要给 AppBundle\Entity\User 实现 JsonSerializable 接口

class T implements JsonSerializable {  private $id;  private $name;  private $pass;  function __construct($id, $name, $pass) {    $this->id = $id;    $this->name = $name;    $this->pass = $pass;  }  function jsonSerialize() {    return array(      'id' => $this->id,      'name' => $this->name,      'pass' => $this->pass,      );  }}$d[] = new T(1, 'a', 'p');$d[] = new T(2, 'b', 'p');echo json_encode($d);
[{"id":1,"name":"a","pass":"p"},{"id":2,"name":"b","pass":"p"}]
否则只能是 [{},{}]
因为返回的属性是私有的



多谢,就是因为属性是私有的。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php怎么解析xml标签里面的内容?Nächster Artikel:开发环境问题