dongyuan1984 2015-05-15 15:13
浏览 35
已采纳

循环时操纵数组

So $tr['tree'] is an array. $dic is an array stored as key values. I want to add the key source to that those arrays. It looks like the following code doesn't work as expected as I'm guessing $dic is a new instance of the array object inside $tr['tree'].

foreach($tr['tree'] as $dic){
    $dic['source'] = $tr['source']." > ".$dic['name'];
}

Note, I'm coming from python where this would work brilliantly. So how would I do this in PHP?

  • 写回答

1条回答 默认 最新

  • douwo1517 2015-05-15 15:17
    关注

    foreach() creates copies of the items you're looping on, so $dic in the loop is detached from the array. If you want to modify the parent array, the safe method is to use:

    foreach($array as $key => $value) {
       $array[$key] = $new_value;
    }
    

    You could use a reference:

    foreach($array as &$value) {
                      ^---
         $value = $new_value;
    }
    

    but that can lead to stupidly-hard-to-find bugs later. $value will REMAIN a reference after the foreach terminates. If you re-use that variable name later on for other stuff, you'll be modifying the array, because the var still points at it.

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

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写