Recursively remove empty elements and subarrays from a multi-dimensional array

后端 未结 6 2063
暖寄归人
暖寄归人 2020-11-27 19:19

I can\'t seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.

My input array may look like this: <

6条回答
  •  难免孤独
    2020-11-27 19:44

    Following up jeremyharris' suggestion, this is how I needed to change it to make it work:

    function array_filter_recursive($array) {
       foreach ($array as $key => &$value) {
          if (empty($value)) {
             unset($array[$key]);
          }
          else {
             if (is_array($value)) {
                $value = array_filter_recursive($value);
                if (empty($value)) {
                   unset($array[$key]);
                }
             }
          }
       }
    
       return $array;
    }
    

提交回复
热议问题