从数组中删除空行

时间:2018-02-27 11:32:20

标签: php arrays array-filter

我想从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,'')
  );

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

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
    )

)

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

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] => ''
        )

)

2 个答案:

答案 0 :(得分:0)

简单的解决方案:

$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>';

答案 1 :(得分:0)

您可以使用loop for filter multidimensional array

Y ~= 45%, K = 0%, A = 100%