php - 无法从嵌套数组中删除空元素

标签 php codeigniter

我有一个数组,$row2

$row2中存在两个数组。 $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] =>
        )

)

我想从数组中删除空元素,但我做不到。

我尝试了以下方法:

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

最佳答案

如果您使用array_map,我有一个单行解决方案可以从多维数组中过滤掉null值。以及array_filter ,

    $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
        )

)

演示:https://eval.in/975240

关于php - 无法从嵌套数组中删除空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49390322/

相关文章:

php - 2 相同的查询数据库返回不同的结果

php - 本地PHP测试环境无法建立MySQL数据库连接

php - 如何使用 CodeIgniter 在数据库中存储和检索图像

php - 如果在 Foreach 循环中

php - 在黑莓上运行 apache、php 和 mysql

php - PHP 中读取请求的向后兼容性

正则表达式 : lookbehind and lookahead and greediness problem

php - mysql 和 php 中的 AES 加密

CodeIgniter 2.1 的 show_404() 和 404_override 问题

php - 菜单不能直接转到页面