2009-10-02 116 views
0

我使用引用来改变一个数组:与PHP数组意外行为参考

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

    $counter++; 
} 

如果我打印数组内容,然后我收到了预期的结果。当我遍历它时,所有元素似乎都是相同的(第一个)。

当我删除内部数组中的参考运算符&时,除非未设置索引,否则一切正常。

+0

我怀疑你在某处重新使用了一个引用变量,忘记它仍然是一个引用。看到其他的代码可能会有所帮助 – Greg 2009-10-02 14:55:58

回答

4

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

+0

在这里找到了另一种解决方案:http://nl2.php.net/manual/en/language.references.whatdo.php#73631但是你的回答更好。 – Ikke 2009-10-02 15:05:01

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

虽然我刚刚改写为“机械性”,所以它可能会无法正常工作。但是要想到如何达到同样的效果,没有副作用。您仍然在修改此循环中的原始数组。

+0

我认为参考文献在这里很合适。那是引用的地方,对吗? – Ikke 2009-10-04 18:38:30

+0

好吧,不完全。你已经有了一个免费的元素(它的关键)的“句柄”,所以实际上没有使用它们的真正优势。参考文献是为了避免数据重复,这里没有发生。事实上,foreach循环中的引用本质上非常混乱,并可能引入微妙的错误。例如,在你的代码中,$ newAppointment和$ appointment将保持设置并且即使在2个循环之后也指向数组的最后一项。以后很容易重用这些名字,并且可能很难理解为什么错误的元素会“意外”改变。 – Palantir 2009-10-05 06:22:07