symfony 使用 findall读取出来的数据 如何转成 json
Jun 20, 2016 pm 12:43 PM
$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);
否则只能是 [{},{}]
因为返回的属性是私有的
你需要给 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);
否则只能是 [{},{}]
因为返回的属性是私有的
多谢,就是因为属性是私有的。

Heißer Artikel

Hot-Tools-Tags

Heißer Artikel

Heiße Artikel -Tags

Notepad++7.3.1
Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version
Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1
Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6
Visuelle Webentwicklungstools

SublimeText3 Mac-Version
Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

11 beste PHP -URL -Shortener -Skripte (kostenlos und Premium)

Arbeiten mit Flash -Sitzungsdaten in Laravel

Erstellen Sie eine React -App mit einem Laravel -Back -Ende: Teil 2, reagieren

Vereinfachte HTTP -Reaktion verspottet in Laravel -Tests

Curl in PHP: So verwenden Sie die PHP -Curl -Erweiterung in REST -APIs

12 Beste PHP -Chat -Skripte auf Codecanyon

Ankündigung von 2025 PHP Situation Survey
