无法从嵌套数组中删除null元素

时间:2018-03-20 17:11:01

标签: php codeigniter

我有一个数组 $ row2 $ row2 2数组中 输出 $ row2

Array
(
    [0] => Array
        (
            [Proposal_id] => 9
            [row] => 1
            [col1] => 2 
            [col2] => 2 
            [col3] =>  
            [col4] =>  
            [col5] =>  
            [Type] => customtbl
            [Invoice_term] =>  
            [Qoute] =>  
            [Rate_per_hour] =>  
            [Total] =>  
        )

    [1] => Array
        (
            [Proposal_id] => 9
            [row] => 2
            [col1] => 3 
            [col2] => 4 
            [col3] =>  
            [col4] =>  
            [col5] =>  
            [Type] => customtbl
            [Invoice_term] =>  
            [Qoute] =>  
            [Rate_per_hour] =>  
            [Total] =>  
        )

)

我想从数组中删除null元素,但我不能这样做 我尝试了以下方法

array_filter($row2);
array_filter($row2, function($var){return !is_null($var);} );
array_diff($rows2,array("null",""));

2 个答案:

答案 0 :(得分:1)

如果您使用array_map以及array_filter,我会使用单线程解决方案过滤掉多维数组中的null值,

    $array = [
    ['Proposal_id' => 9,
     'row' => 1,
     'col1' => 2, 
     'col2' => 2, 
     'col3' => null,
     'col4' => null,
     'col5' =>  null,
     'Type' => 'customtbl',
     'Invoice_term' => null,  
     'Qoute' => null,
     'Rate_per_hour' => null,  
     'Total' => null,
    ],
    [   
        'Proposal_id' => 9,
        'row' => 1,
        'col1' => 2, 
        'col2' => 2 ,
        'col3' => null,
        'col4' => null,
        'col5' =>  null,
        'Type' => 'customtbl',
        'Invoice_term' => null,  
        'Qoute' => null,
        'Rate_per_hour' => null,  
        'Total' => null,
    ]
];
$af = array_filter(array_map('array_filter', $array));
print '<pre>';
print_r($af);
print '</pre>';

<强>输出:

 Array
(
    [0] => Array
        (
            [Proposal_id] => 9
            [row] => 1
            [col1] => 2
            [col2] => 2
            [Type] => customtbl
        )

    [1] => Array
        (
            [Proposal_id] => 9
            [row] => 1
            [col1] => 2
            [col2] => 2
            [Type] => customtbl
        )

)

DEMO https://eval.in/975240

答案 1 :(得分:1)

array_filter中使用array_map。 请记住,您可能希望运行不同的条件而不是if($value),因为这将不仅验证空值,还验证零和空字符串。

array_map(function($var) {
    return array_filter($var, function($value) {
        if ( !is_null($value) )
            return $value;
    });
},$row2);