doubo1883 2013-10-23 06:41
浏览 49
已采纳

如何在Doctrine中编码JSON数组?

How can I convert an Array into JSON in Doctrine ?

So far I have tried this.Here is my code:

require_once ("../Users.php");
require_once("../../test/doctrine/cli-config.php");
require_once "../../test/doctrine/bootstrap.php";

            $user_list = array();

            $usersRepository = $entityManager->getRepository('Users');

            $users = $usersRepository->findAll();  

            echo "<pre>";
            print_r($users);

            foreach ($users as $user) 
            {
                $user_list[] = array('user_list'=>$user);   
            }


  json_encode($user_list)

The print_r() section is returning me this:

Array
(
    [0] => Users Object
        (
            [id:Users:private] => 1
            [lastName:Users:private] => User1
            [firstName:Users:private] => Test1
            [city:Users:private] => ABC
            [country:Users:private] => XYZ
            [email:Users:private] => user1@yahoo.com
        )

    [1] => Users Object
        (
            [id:Users:private] => 2
            [lastName:Users:private] => User2
            [firstName:Users:private] => Test1
            [city:Users:private] => ABC
            [country:Users:private] => XYZ
            [email:Users:private] => user2@yahoo.com
        )

)
[{"user_list":{}},{"user_list":{}}]

See the Json Response is Empty. Can anyone help me with that?

  • 写回答

1条回答 默认 最新

  • doukuang8166 2013-10-23 06:53
    关注

    You do not have public properties in your entities... that's why you get an empty json.

    I am using for this purpose EntitySerializer

    Usage for your case should be:

    $eSerializer = new Bgy\Doctrine\EntitySerializer($entityManager);
    $result = $eSerializer->toArray($users);
    

    but this is just a personal preference. You could an should use the standard Serializer class of Symfony framework

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改