从数组中删除空行

remove empty rows from array

我想从 php 中的数组中删除空行,我使用 array_filter 给出了完美的结果。 这是我试过的代码

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("",'','')
  );

  $cars= array_filter(array_map('array_filter', $cars));

  echo "<pre>"; print_r($cars);

the output is following for above array is :-

Array
(
    [0] => Array
        (
            [0] => Volvo
            [1] => 22
            [2] => 18
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
            [2] => 13
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
            [2] => 2
        )

)

输出是完美的,因为它删除了空行,但是当我像下面这样创建新数组时

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("",54,'')
  );

在最后一个数组中,它删除了第一列和最后一列,并使其保留在数组中的第一个位置列。如下所示:-

Array
(
    [0] => Array
    (
        [0] => Volvo
        [1] => 22
        [2] => 18
    )

    [1] => Array
    (
        [0] => BMW
        [1] => 15
        [2] => 13
    )

    [2] => Array
    (
        [0] => Saab
        [1] => 5
        [2] => 2
    )

    [3] => Array
    (
        [1] => 54
    )

)

我只想删除空行而不是列,所以数组 return 应该如下所示

Array
(
    [0] => Array
        (
            [0] => Volvo
            [1] => 22
            [2] => 18
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 15
            [2] => 13
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 5
            [2] => 2
        )

    [3] => Array
        (
            [0] => ''
            [1] => 54
            [2] => ''
        )

)

简单的解决方案:

$cars = array
(
    array("Volvo",22,18),
    array("BMW",15,13),
    array("Saab",5,2),
    array("",'','')
);

// Here we `implode` all values of current subarray 
// and if this imploded string is empty - skip subarray
$cars = array_filter($cars, function($v) { return implode('', $v) !== ''; });
echo '<pre>', print_r($cars), '</pre>';

您可以使用循环来过滤多维数组

$valueArray = array();
foreach ( $cars as $value ) {
    $valueArray[] = array_filter($value);
}
echo '<pre>'; print_r($valueArray);