用foreach php填充一个关联数组

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

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

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++;
}

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