2014-02-21 67 views
2

我想从一个实体多维数组。转换实体到阵列中的Symfony

Symfony Serializer已经可以转换成XML,JSON,YAML等,而不是一个数组。

我需要转换,因为我希望有一个干净的var_dump。我现在拥有很少连接的实体,完全不可读。

我该如何做到这一点?

+0

可能重复[?如何获得Doctrine2结果对象作为关联数组(http://stackoverflow.com/questions/7259256/how-to-get-a -doctrine2-result-object-as-an-associative-array) – denys281

+0

我不想得到restult作为数组 - 我使用它作为实体和需要在其他plaace转换为数组。 –

+0

调试应用程序比“var_dumps”要好得多。尝试使用xdebug - 这个工具作为debuger非常棒。 – Cyprian

回答

4

转换现有的实体对象数组

使用get_object_vars() PHP函数:

在PHP控制器:

$properties = get_object_vars($entity); 
return $this->container->get('templating')->renderResponse(
    'YourOwnBundle:Entity:array.html.twig', 
    array(
     'properties' => $properties 
     ) 
    ) 
; 

在嫩枝模板:

<table> 
    {% for key, value in properties %} 
     <tr> 
      <td>{{ value }}</td> 
      <td>{{ key }}</td> 
     </tr> 
    {% endfor %} 
</table> 

注:最佳实践是f ORMAT直接存储库的实体(见下文)数组形式

获取实体从资料库查询

在你EntityRepository,你可以选择你的实体,并指定要与getArrayResult()方法的数组。
欲了解更多信息,请参阅Doctrine query result formats documentation

public function findByIdThenReturnArray($id){ 
    $query = $this->getEntityManager() 
     ->createQuery("SELECT e FROM YourOwnBundle:Entity e WHERE e.id = :id") 
     ->setParameter('id', $id); 
    return $query->getArrayResult(); 
} 

如果所有不符合你应该去看看PHP文档中关于ArrayAccess接口。
它检索的属性是这样的:echo $entity['Attribute'];

+0

getArrayResult没有实体转换为数组 - 我有实体,并希望将其转换为阵列 –

+0

@。 GrekHmhmm我已经更新了我的答案:**使用get_object_vars($实体)** –

+1

get_object_vars($实体)返回我的应用程序空2.6 – crafter