0

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

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

    $counter++;
}

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

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

4

2 回答 2

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

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

于 2009-10-02T14:59:20.293 回答
4

如果这样做,则必须在退出循环时取消设置 $newAppointment。这是相关条目

于 2009-10-02T14:56:11.173 回答