doxn43207 2017-09-27 15:44
浏览 103
已采纳

在foreach中修改数组并理解原因的问题

I always did something like

e.g. from my last project in Laravel

foreach( $sections as $section )
{
    $section->date = Carbon::parse($section->date)->diffForHumans();
}

And it worked well. Never problem with that, array was modified as I wanted

But now I did this

$events = $this->events;
        foreach($events as $event)
        {
            $date = new \DateTime($event['date']);
            $event['date'] = (int)$date->format('d');
            echo $event['date'];
            var_dump($event);
        }
        var_dump($events);
        $this->events = $events;

And it doesn't work as I want, different values inside loop and outside loop.

I was looking what is bad and I found what it is about, to give & or do foreach $key => $value...

But it would be okay.

But it isn't.

Because I know. I remember. I did many times just something like

foreach($a as $b)
{
    $b = .......
}

And it worked. But now it isn't.

So I don't understand. But I have to and want to.

I was searching for answer, but can find it.

Why for one time it works for me like that, and other time doesn't work and I need apersand or key => value playing?

Please give me understanding <3

Why one time it is working but another not.

  • 写回答

1条回答 默认 最新

  • drpph80800 2017-09-27 15:58
    关注

    foreach iterates over a copy of the array, so modifications to the array elements are only made to that temporary copy unless you create a reference:

    foreach($a as &$b) {
        $b = 'something';
    }
    

    Or modify the original array by key:

    foreach($a as $k => $b) {
        $a[$k] = 'something';
    }
    

    For an array of objects, the array is a copy but the objects in the copy are references to the original array. So modifications to the objects in the copy are reflected in the original array:

    foreach($a as $b) {
        $b->var = 'something';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于c++外部库文件宏的问题,求解
  • ¥15 office打开卡退(新电脑重装office系统后)
  • ¥300 FLUENT 火箭发动机燃烧EDC仿真
  • ¥15 【Hadoop 问题】Hadoop编译所遇问题hadoop-common: make failed with error code 2
  • ¥15 vb6.0+webbrowser无法加载某个网页求解
  • ¥15 RPA财务机器人采购付款流程
  • ¥15 计算机图形多边形及三次样条曲线绘制
  • ¥15 根据protues画的图用keil写程序
  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误