取消设置不在多个foreach语句中工作(PHP)

时间:2013-08-08 10:47:25

标签: php

有人可以告诉我这段代码有什么问题:

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)之后,数据数组似乎相同且未设置无效

2 个答案:

答案 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将以这种方式工作