2

如何在 Doctrine 中将 Array 转换为 JSON?

到目前为止,我已经尝试过了。这是我的代码:

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)

print_r() 部分返回给我这个:

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":{}}]

请参阅 Json 响应为空。任何人都可以帮助我吗?

4

1 回答 1

4

您的实体中没有公共属性......这就是为什么您会得到一个空的 json。

我为此目的使用EntitySerializer

您的案例的用法应该是:

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

但这只是个人喜好。您可以使用Symfony 框架的标准 Serializer 类

于 2013-10-23T06:53:58.837 回答