【问题标题】:Unexpected behaviour with PHP array referencesPHP 数组引用的意外行为
【发布时间】:2010-12-03 08:35:01
【问题描述】:

我正在使用引用来改变数组:

foreach($uNewAppointments as &$newAppointment)
{
    foreach($appointments as &$appointment)
    {
        if($appointment == $newAppointment){
            $appointment['index'] = $counter;
        }
    }
    $newAppointment['index'] = $counter;
    $newAppointments[$counter] = $newAppointment;

    $counter++;
}

如果我打印数组内容,那么我会收到预期的结果。当我迭代它时,所有元素似乎都是相同的(第一个)。

当我删除内部数组中的引用运算符 & 时,一切正常,除了未设置索引。

【问题讨论】:

  • 我怀疑你在某处重复使用了一个引用变量,忘记了它仍然是一个引用。查看其余代码可能会有所帮助

标签: php loops foreach pass-by-reference


【解决方案1】:

在 foreach 循环中使用引用是自找麻烦 :) 我已经多次这样做了,而且我总是重写该代码。

你也应该这样做。像这样:

foreach($uNewAppointments as $newAppointmentKey => $newAppointment)
{
        foreach($appointments as $appointmentKey => $appointment)
        {
                if($appointment == $newAppointment){
                        appointments[$appointmentKey]['index'] = $counter;
                }
        }
        $uNewAppointments[$newAppointmentKey]['index'] = $counter;
        $$uNewAppointments[$newAppointmentKey][$counter] = $newAppointment;

        $counter++;
}

虽然我只是“机械地”重写了它,但它可能无法正常工作。但这是为了了解如何在没有副作用的情况下达到相同的效果。您仍在此循环中修改原始数组。

【讨论】:

  • 我认为参考文献在这里很合适。那就是引用的地方,对吧?
  • 嗯,不完全是。您已经免费获得了元素(它的键)的“句柄”,因此实际上使用它们并没有真正的优势。引用是为了避免数据重复,这里不会发生。事实上,foreach 循环中的引用本质上是非常混乱的,并且可能会引入一些细微的错误。例如,在您的代码中,即使在 2 个循环之后,$newAppointment 和 $appointment 仍将保持设置并指向数组的最后一项。以后很容易重复使用这些名称,并且可能很难理解为什么错误的元素会“意外”更改。
【解决方案2】:

如果您这样做,您必须在退出循环时取消设置 $newAppointment。这是relevant entry

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 2016-11-08
  • 2018-10-22
  • 2012-07-22
相关资源
最近更新 更多