如何遍历symfony(Doctrine)结果对象


How to iterate through a symfony (Doctrine) result object

我有以下查询:

function indexAction()
{
    $u = $this->getDoctrine()->getRepository("AppBundle:Users")->findAll( 'Doctrine'ORM'AbstractQuery::HYDRATE_ARRAY );
    return $this->render("default/test.html.twig", ["users" => $u]);
}

我在Twig模板中循环使用这个循环:

{%  for item in users %}
<li>{{ item.email }} : </li>
{%  endfor %}

我遇到了这个错误:

Impossible to access a key "name" on an object of class "AppBundle'Entity'Users" that does not implement ArrayAccess interface in default/test.html.twig at line

您的类是否在实体定义中实现了ArrayAccess?

class Foo implements ArrayAccess

你必须在你的类中添加几个方法才能做到这一点:

要实现ArrayAccess,您需要实现四个方法:offsetExists、offsetGet、offsetSet和offsetUnset。ArrayAccess::offsetExists必须返回布尔值,offsetGet可以返回任何有效的PHP类型,而offsetSet和offsetUnset不应返回任何值。一旦实现了这些方法,就可以将对象视为数组来保存和检索属性

更多详细信息请点击此处。

出现问题。将users变量传递给模板,但在for循环中使用myItems

试试这个:

{% for item in users %}
    {{ dump(item) }}<br />
{% endfor %}