将实体转换为Symfony中的数组 [英] Convert Entity to array in Symfony
问题描述
我试图从一个实体获取一个多维数组。
I'm trying to get a multi-dimensional array from an Entity.
Symfony Serializer 可以转换为XML,JSON,YAML等,但不能转换为数组。
Symfony Serializer can already convert to XML, JSON, YAML etc. but not to an array.
我需要转换,因为我想要一个干净的 var_dump
。我现在拥有几乎没有连接的实体,完全不可读。
I need to convert because I want have a clean var_dump
. I now have entity with few connections and is totally unreadable.
如何实现?
推荐答案
将现有实体对象转换为数组
使用 get_object_vars() PHP函数:
在PHP控制器中:
$properties = get_object_vars($entity);
return $this->container->get('templating')->renderResponse(
'YourOwnBundle:Entity:array.html.twig',
array(
'properties' => $properties
)
)
;
在TWIG模板中:
<table>
{% for key, value in properties %}
<tr>
<td>{{ value }}</td>
<td>{{ key }}</td>
</tr>
{% endfor %}
</table>
注意:最佳做法是将库中的实体格式化(<
Note : Best practice is to format your entity in repository directly (see below)
从存储库查询获取数组格式的实体
在您的EntityRepository中,您可以选择您的实体,并指定需要一个 getArrayResult()
方法的数组。
有关更多信息,请参阅< a href =http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#query-result-formats =nofollow> 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();
}
你应该去看看关于 ArrayAccess 界面的PHP文档。 >
它以这种方式检索属性: echo $ entity ['Attribute'];
If all that doesn't fit you should go see the PHP documentation about ArrayAccess interface.
It retrieves the attributes this way : echo $entity['Attribute'];
这篇关于将实体转换为Symfony中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!