MENU

PHP去除(多维)数组中的空数组

December 13, 2019 • Read: 198 • PHP

先贴上原代码(原文链接):

function array_no_empty($arr) {
    if (is_array($arr)) {
        foreach ( $arr as $k => $v ) {
            if (empty($v)) unset($arr[$k]);
            elseif (is_array($v)) {
                $arr[$k] = array_no_empty($v);
            }
        }
    }
    return $arr;
}

确实确实可以去除空数组,但对于多维数组还是清理得不够干净,如下:

array(5) {
  [1]=>
  array(1) {
    ["src"]=>
    string(51) "http://wp.com/wp-content/uploads/2019/12/x_bg02.jpg"
  }
  [2]=>
  array(1) {
    ["src"]=>
    string(51) "http://wp.com/wp-content/uploads/2019/12/x_bg10.jpg"
  }
  [3]=>
  array(1) {
    ["src"]=>
    string(0) ""
  }
  [4]=>
  array(1) {
    ["src"]=>
    string(0) ""
  }
  [5]=>
  array(1) {
    ["src"]=>
    string(0) ""
  }
}

清理后的结果如下:

array(5) {
  [1]=>
  array(1) {
    ["src"]=>
    string(51) "http://wp.com/wp-content/uploads/2019/12/x_bg02.jpg"
  }
  [2]=>
  array(1) {
    ["src"]=>
    string(51) "http://wp.com/wp-content/uploads/2019/12/x_bg10.jpg"
  }
  [3]=>
  array(0) {
  }
  [4]=>
  array(0) {
  }
  [5]=>
  array(0) {
  }
}

故修改代码如下:

function array_no_empty($arr) {
    if (is_array($arr)) {
        foreach ( $arr as $k => $v ) {
            if (empty($v)){
                unset($arr[$k]);
            } elseif (is_array($v)) {
                $arr[$k] = array_no_empty($v);
            }
        }
    }
    return array_filter($arr);
}

清理结果如下:

array(2) {
  [1]=>
  array(1) {
    ["src"]=>
    string(51) "http://wp.com/wp-content/uploads/2019/12/x_bg02.jpg"
  }
  [2]=>
  array(1) {
    ["src"]=>
    string(51) "http://wp.com/wp-content/uploads/2019/12/x_bg10.jpg"
  }
}