问题
I'm using references to alter an array:
foreach($uNewAppointments as &$newAppointment)
{
foreach($appointments as &$appointment)
{
if($appointment == $newAppointment){
$appointment['index'] = $counter;
}
}
$newAppointment['index'] = $counter;
$newAppointments[$counter] = $newAppointment;
$counter++;
}
If I print the array contents, then I receive the expected result. When I iterate over it, all elements seem to be the same (the first).
When I remove the reference operator & in the inner array, all goes normal, except index isn't set.
回答1:
If you do this, you must unset $newAppointment when you exit the loop. Here is the relevant entry.
回答2:
Using references in foreach loops is asking for trouble :) I've done that several times, and I always rewrote that code.
You should to it as well. Like this:
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++;
}
Though I have just rewritten it "mechanically", so it will probably not work. But it's to get the idea of how to achieve the same effect, without the side effects. You are still modifying the original arrays in this loop.
来源:https://stackoverflow.com/questions/1509979/unexpected-behaviour-with-php-array-references