1

Why is this only give me the last value and not all the values in my db?

    $em = $this->getDoctrine()->getManager();
    $repo = $em->getRepository('ErpBundle:Sponsor');
    $clients = $repo->findAll();
    $array = array();
    foreach ($clients as $key =>$client){
        $array['id'] = $client->getId();
        $array['value'] = $client->getName();
    }
   return $array

3 Answers 3

2

you are overwriting your array, try this..

foreach ($clients as $key =>$client){
    $array[$key]['id'] = $client->getId();
    $array[$key]['value'] = $client->getName();
}

I don't know your $key's value, if you are ok with $key use it or you can use counter variable for newly generated array.

$i=0;
foreach ($clients as $key =>$client){
    $array[$i]['id'] = $client->getId();
    $array[$i]['value'] = $client->getName();
    $i++;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You're overwriting values in array try this:

$clients = $repo->findAll();
$rows = array();

foreach ($clients as $client){

    $rows[] = array(
        'id' => $client->getId(),
        'name' => $client->getName()
    );

}

return $rows;

Or you can use array_map function.

return array_map(function($client){

    return array(
        'id' => $client->getId(),
        'name' => $client->getName()
    );

}, $repo->findAll());

Comments

0

with $array['id'] = $client->getId(); and $array['value'] = $client->getName(); you are overwriting your $array[...] everytime. if your logic "reads" the last element of your loop, then the last element is in your $array

// update

you may do something like this:

foreach ($clients as $key =>$client){
   $array[]['id'] = $client->getId();
   $array[]['value'] = $client->getName();
}

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.