Symfony 存储 foreach 循环的结果

Deg*_*egu 3 php symfony

我想知道是否可以存储 foreach 循环的结果。我不知道如何更详细地解释我的问题。

所以可以说以下让我得到 3 个不同的数组

$events = $this->getDoctrine()->getRepository('TestBundle:Events')->findBy(array('event' => $eventId));
Run Code Online (Sandbox Code Playgroud)

#name,color#

1. 派对,粉色
2. 泳池派对,蓝色
3. 生日,红色

foreach $events避免非对象调用。

foreach($events as $e)
{
    $name = $e->getName();
    $color = $e->getColor();
}
Run Code Online (Sandbox Code Playgroud)

现在我可以将数组返回到 twig 并 for 循环它们,但是我可以将它们存储到控制器中的数组中吗?

我当前的代码

$events = 
$this->getDoctrine()->getRepository('TestBundle:Events')->findBy(array('event' => $eventId));

foreach($events as $e)
{                   
    $name = $e->getName();
    $color = $e->getColor();

    $array = array(array("$name", "$color"));
}

return new JsonResponse($array);
Run Code Online (Sandbox Code Playgroud)

这样我只得到最后一个数组。在本例中,生日为红色。希望有人能帮我解答我的问题。感谢您抽出时间!

Ano*_*ous 5

您需要将结果存储在循环之外,以便在迭代之间保留它。根据你想要的,它看起来像:

$output = array();

foreach($events as $event)
{
    $output[$event->getName()] = $event->getColor();
}

return new JsonResponse($output);
Run Code Online (Sandbox Code Playgroud)

...或者像这样...

$output = array();

foreach($events as $event)
{
    $output[] = array($event->getName(), $event->getColor());
}

return new JsonResponse($output);
Run Code Online (Sandbox Code Playgroud)

前者的输出看起来像{"B-day": "red", ...},而后者的输出看起来像[["B-day", "red"], ...]


您通常会选择前一个输出,因为建议用于 AJAX 的 JSON 中最外层的类型是对象,而不是数组(出于安全原因)。