无法使用foreach循环将键值数组设置为数组

<?php
$array = array(
    array('key' => 'value'),
    array('key' => 'value'),
    array('key' => 'value')
);

foreach($array as $a) {
    $a['anotherkey'] = 'anothervalue';
}
?>

I am trying to add another key value ('anotherkey' => 'anothervalue') into each array inside $array. However the above code does not work and I can't seem to figure out why, is it because the $a['anotherkey'] could not add the value to the real array ? And what is the proper way to adding the keyvalue pair into each of the array inside $array using foreach loop ? Thank you.

Try this:

 $array = array(
   array('key' => 'value'),
   array('key' => 'value'),
   array('key' => 'value')
);

foreach($array as &$a) {
  $a['anotherkey'] = 'anothervalue';
}

print_r($array);

Pass By Reference used above. Read here : http://php.net/manual/en/language.references.pass.php

Hope this helps.