douwei2966 2017-05-20 03:19
浏览 47
已采纳

无法使用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.

  • 写回答

1条回答 默认 最新

  • douzai2562 2017-05-20 03:23
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面