有人可以告诉我这段代码有什么问题:
foreach ($data as $region ):
foreach ($region as $type):
foreach ($type as $type2):
foreach ($type2 as $key=>$val):
if ($val=='background-color: FFFFFF;' || $val=='') unset($type2[$key]);
endforeach;
endforeach;
endforeach;
endforeach;
在print_r($data)
之后,数据数组似乎相同且未设置无效
答案 0 :(得分:2)
您的循环正在原始元素的副本上运行; $type2
中不会显示对$data
的更改,因为$type2
是副本。
您可以通过按键迭代所有数组来解决此问题,然后使用这些键索引到$data
以删除值:
foreach ($data as $k1 => $region ):
foreach ($region as $k2 => $type):
foreach ($type as $k3 => $type2):
foreach ($type2 as $k4 =>$val):
if ($val=='background-color: FFFFFF;' || $val=='') {
unset($data[$k1][$k2][$k3][$k4]);
}
endforeach;
endforeach;
endforeach;
endforeach;
当然这很丑陋,但这是四个嵌套循环。如果通过引用迭代而不是抓取键,也有选项,但我个人不喜欢,因为通过在循环结束后重用废弃的引用来编写错误的好机会。特别是在这种情况下,我不喜欢它的第四种力量。
答案 1 :(得分:-1)
使用它,它应该工作:
foreach ($data as &$region ):
foreach ($region as &$type):
foreach ($type as &$type2):
foreach ($type2 as $key=>$val):
if ($val=='background-color: FFFFFF;' || $val=='') unset($type2[$key]);
endforeach;
endforeach;
endforeach;
endforeach;
由于&
i放在值变量之前,数组值作为参考传递。 unset将以这种方式工作