1

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!

Anonymous
  • 10,357
  • 3
  • 37
  • 49
Degu
  • 168
  • 1
  • 1
  • 10

2 Answers2

4

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

Anonymous
  • 10,357
  • 3
  • 37
  • 49
1

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.

Peter Bailey
  • 101,481
  • 30
  • 175
  • 199