Loop through multi-dimensional array and remove certain keys

前端 未结 2 450
南方客
南方客 2021-01-21 18:19

I\'ve got a nested tree structure which is based on the array below:

Array
(
    [1] => Array
        (
            [id] => 1
            [parent] => 0
            [n         


        
相关标签:
2条回答
  • 2021-01-21 19:13

    Solved it! Added this function to my class:

    private function cleanTree(&$arr){
        foreach($arr as $key => &$item) {
            if(!$item["child"] && empty($item["basename"])){
                unset($arr[$key]);

        }elseif(is_array($item["child"])){
            if(count($item["child"]) == 0){
                unset($arr[$item["id"]]);
            }else{
                $this->cleanTree($item["child"]);
            }
        }
    }
    

    }

    To remove unnecessary elements on the ROOT level(s) as well as anyone else, just run the above twice.

    0 讨论(0)
  • 2021-01-21 19:16

    Rather than putting the test for which elements to destroy in the search function, pass a function to test for targets.

    function searchAndDestroy(&$a, $targetp){
        foreach($a as $k => &$v){
            if(is_array($v)){
                searchAndDestroy($v, $targetp);
            } 
            if ($targetp($k, $v)) {
                unset($a[$k]);
            }
        }
    }
    
    searchAndDestroy($menu, function ($k, $v) {
            return is_array($v) 
                && array_key_exists('basename', $v) && empty($v['basename'])
                && (empty($v['child']) || count($v['child']) == 0);
        });
    

    For PHP < 5.3 (or if you call searchAndDestroy with that function in more than one spot), name the function and pass the name rather than an anonymous function.

    0 讨论(0)
提交回复
热议问题