3

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!

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.