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

之后print_r($data)似乎数据数组相同并且未设置不起作用

4

2 回答 2

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;

当然这很难看,但那是四个嵌套循环就可以了。如果通过引用迭代而不是抓取键,也可以选择,但我个人不喜欢这样,因为在循环结束后通过重用废弃的引用来编写错误的好机会。特别是在这种情况下,我不喜欢它的四次方。

于 2013-08-08T10:49:40.137 回答
-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 将以这种方式工作

于 2013-08-08T10:51:13.587 回答