从多维PHP数组和rebase索引中删除项

时间:2015-08-04 19:07:18

标签: php arrays multidimensional-array

我有这个数组,我需要删除inTOC is 0 (ie. false)中的任何项目,同时保持索引能够使用for循环。

这是数组:

Array
(
    [0] => Array
        (
            [name] => JAL
            [id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
            [inTOC] => 1
            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => BRU
                            [id] => 5600b395-4a28-4956-ccbf-9b238c4fa432
                            [inTOC] => 0
                        )
                    [1] => Array
                        (
                            [name] => TEW
                            [id] => 9e2ebbf6-1c81-4ff7-feb5-c5bede2ccd6c
                            [inTOC] => 1
                        )
                )
        )

    [1] => Array
        (
            [name] => ABC
            [id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
            [inTOC] => 1
        )

)

这是我到目前为止的功能,我尝试unset没有重新绑定,array_splice只删除子节点,目标是删除数组:

public function tocFilterNonTOC($tree){
      $size = count($tree);
      for ($i = 0; $i < $size; $i++) {
        if ($tree[$i]['inTOC']) {
           $this->tocFilterNonTOC($tree[$i]['children']);
         } else {
           array_splice($tree[$i], $i, 1); // removes the 'name' node (BRU) only
        }
      }
   }

1 个答案:

答案 0 :(得分:0)

最后,我回到使用unset,但将array_values添加到递归函数中,如下所示:

public function tocFilterNonTOC($tree){
      $size = count($tree);
      for ($i = 0; $i < $size; $i++) {
        if ($tree[$i]['inTOC']) {
           $this->tocFilterNonTOC($tree[$i]['children']);
         } else {
           unset($tree[$i]);
        }
      }
      if ($tree!=null && is_array($tree)) $tree = array_values($tree)
}