PHP数组引用的意外行为

时间:2009-10-02 14:47:08

标签: php loops foreach pass-by-reference

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

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

    $counter++;
}

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

当我删除内部数组中的引用运算符& 时,除了未设置索引外,所有内容都正常。

2 个答案:

答案 0 :(得分:5)

在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++;
}

虽然我刚刚“机械地”重写了它,但它可能无法正常工作。但它是为了获得如何实现相同效果的想法,没有副作用。您仍在此循环中修改原始数组。

答案 1 :(得分:4)

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