Ikk*_*kke 0 php foreach loops pass-by-reference
我正在使用引用来改变数组:
foreach($uNewAppointments as &$newAppointment)
{
foreach($appointments as &$appointment)
{
if($appointment == $newAppointment){
$appointment['index'] = $counter;
}
}
$newAppointment['index'] = $counter;
$newAppointments[$counter] = $newAppointment;
$counter++;
}
Run Code Online (Sandbox Code Playgroud)
如果我打印数组内容,那么我会收到预期的结果.当我迭代它时,所有元素似乎都是相同的(第一个).
当我删除引用运算符&在内部数组中时,除了未设置索引外,一切正常.
在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++;
}
Run Code Online (Sandbox Code Playgroud)
虽然我刚刚"机械地"重写了它,但它可能无法正常工作.但它是为了获得如何实现相同效果的想法,没有副作用.您仍在修改此循环中的原始数组.