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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用