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.

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

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站