消除空值嵌套数组php

时间:2017-07-18 12:42:01

标签: php arrays

我有一个嵌套在原始数组中的数组和内容。数组的内容看起来像 -

$ myArray的

[0] => Array(
[ID] => 1
[Fruit] => Apple
[State] => Ohio
[description]
   Array(
     [0] => This is sample description
     [1] => This is sample description 2
     [2] => 
     [3] => 
     [4] => 


)
 [price]
   Array(
     [0] => 20
     [1] => 15
     [2] => 
     [3] => 
     [4] => 
)
[1] => Array(
[ID] => 1
[Fruit] => Apple
[State] => Ohio
[description]
   Array(
     [0] => This is sample description
     [1] => This is sample description 2
     [2] => 
     [3] => 
     [4] => 
)
[price]
   Array(
     [0] => 20
     [1] => 15
     [2] => 
     [3] => 
     [4] => 
)

我想摆脱嵌套数组中的null值。当我使用以下内容时:

$newArray = array();
foreach ($firstArray as $row){
    if ($row !== null)
        $newArray[] = $row;

}
echo $newArray;

新数组没有消除数组中的null值。

1 个答案:

答案 0 :(得分:3)

你可以这样做: -

function array_filter_to_each_sub_array_recursively($input){
    foreach ($input as &$value){
        if (is_array($value)){
            $value = array_filter_to_each_sub_array_recursively($value);
        }
    }
    return array_filter($input);
}

$myArray = array_filter_to_each_sub_array_recursively($myArray);

print_r($myArray);

输出: - https://eval.in/833982