Symfony storing results of foreach loop

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

So lets say following gets me 3 different arrays

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

#name,color#

1. Party, pink
2. Poolparty, blue
3. B-day, red

and foreach $events to avoid non-object call.

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

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

My current code

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

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

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


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).


While this doesn't directly answer your question, it looks like you're building a json API of some sort. If that's true, I'd highly recommend using something like Fractal to do this type of entity >> api conversion.

链接地址: http://www.djcxy.com/p/8388.html

上一篇: Javascript对象VS JSON

下一篇: Symfony存储foreach循环的结果