Symfony 存储 foreach 循环的结果 [英] Symfony storing results of foreach loop

查看:29
本文介绍了Symfony 存储 foreach 循环的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering if is it possible to store results of foreach loop. I dont know how to explain my question more detailed.

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

So lets say following gets me 3 different arrays

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

#name,color#

1.派对,粉红色
2. 泳池派对,蓝色
3. B-day,红色

foreach $events 避免非对象调用.

and foreach $events to avoid non-object call.

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

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

Now I could just return array to twig and for loop them, but can I store them into arrays in controller?

我当前的代码

$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);

有了这个,我只得到最后一个数组.在这种情况下B 天,红色.希望有人能帮助我解决我的问题.感谢您的时间!

With this I get only last array. In this case B-day, red. Hopefully someone can help me out with my question. Thanks for time!

推荐答案

您需要将结果存储在循环之外,以便在迭代之间保持不变.根据您的需要,它看起来像:

You need to store the result outside of the loop for it to be persisted between iterations. Depending on what you want, it would look like:

$output = array();

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

return new JsonResponse($output);

...或者像这样...

...or like this...

$output = array();

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

return new JsonResponse($output);

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

The output of the former looks like {"B-day": "red", ...} while the latter looks like [["B-day", "red"], ...].

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

You would normally pick the former output because it is recommended that the outermost type in JSON used for AJAX be an object, not an array (for security reasons).

这篇关于Symfony 存储 foreach 循环的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆