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';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样