php 在 Symfony 中将实体转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21935593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Entity to array in Symfony
提问by Developer
I'm trying to get a multi-dimensional array from an Entity.
我正在尝试从实体获取多维数组。
Symfony Serializercan already convert to XML, JSON, YAML etc. but not to an array.
Symfony Serializer已经可以转换为 XML、JSON、YAML 等,但不能转换为数组。
I need to convert because I want have a clean var_dump. I now have entity with few connections and is totally unreadable.
我需要转换,因为我想要一个干净的var_dump. 我现在的实体连接很少,完全无法阅读。
How can I achieve this?
我怎样才能做到这一点?
回答by Antoine Subit
Apparently, it is possible to cast objects to arrays like following:
显然,可以将对象转换为数组,如下所示:
<?php
class Foo
{
public $bar = 'barValue';
}
$foo = new Foo();
$arrayFoo = (array) $foo;
var_dump($arrayFoo);
This will producesomething like:
这将产生类似的东西:
array(1) {
["bar"]=> string(8) "barValue"
}
If you have got private and protected attributes see this link : https://ocramius.github.io/blog/fast-php-object-to-array-conversion/
如果您有私有和受保护的属性,请参阅此链接:https: //ocramius.github.io/blog/fast-php-object-to-array-conversion/
Get entity in array format from repository query
从存储库查询中获取数组格式的实体
In your EntityRepository you can select your entity and specify you want an array with getArrayResult()method.
For more informations see Doctrine query result formats documentation.
在您的 EntityRepository 中,您可以选择您的实体并指定您想要一个带有getArrayResult()方法的数组。
有关更多信息,请参阅Doctrine 查询结果格式文档。
public function findByIdThenReturnArray($id){
$query = $this->getEntityManager()
->createQuery("SELECT e FROM YourOwnBundle:Entity e WHERE e.id = :id")
->setParameter('id', $id);
return $query->getArrayResult();
}
If all that doesn't fit you should go see the PHP documentation about ArrayAccessinterface.
It retrieves the attributes this way : echo $entity['Attribute'];
如果所有这些都不适合,您应该查看有关ArrayAccess接口的 PHP 文档。
它以这种方式检索属性:echo $entity['Attribute'];
回答by Skylord123
You can actually convert doctrine entities into an array using the built in serializer. I actually just wrote a blog post about this today: https://skylar.tech/detect-doctrine-entity-changes-without/
您实际上可以使用内置的序列化程序将学说实体转换为数组。实际上,我今天刚刚写了一篇关于此的博客文章:https: //skylar.tech/detect-doctrine-entity-changes-without/
You basically call the normalize function and it will give you what you want:
你基本上调用了 normalize 函数,它会给你你想要的:
$entityAsArray = $this->serializer->normalize($entity, null);
I recommend checking my post for more information about some of the quirks but this should do exactly what you want without any additional dependencies or dealing with private/protected fields.
我建议查看我的帖子以获取有关某些怪癖的更多信息,但这应该完全符合您的要求,无需任何额外的依赖项或处理私有/受保护的字段。

