如果整个数组中所有元素的值均为空白,则完全删除元素

时间:2019-04-30 22:32:07

标签: php multidimensional-array

$arr = [
    [
        'RecordCount' => 1938,
        'CardNumber' => null,
        'CompanyID' => null,
        'RecordRequest' =>null,
        'RecordStatus' => 26
    ],
    [
        'RecordCount' => 2622,
        'CardNumber' => 5786,
        'CompanyID' =>null,
        'RecordRequest' =>null,
        'RecordStatus' => 26
    ],
    [
        'RecordCount' => 2874,
        'CardNumber' => 2874,
        'CompanyID' =>null,
        'RecordRequest' =>null,
        'RecordStatus' => 26    
    ]
];

是否存在一个可以从阵列中完全删除companyID和RecordRequest的函数,因为它们的值在整个阵列中都是空白的?它将保留cardNumber,因为在整个阵列中不为空。 返回:

[0] => Array(
    [RecordCount] => 1938
    [CardNumber] => null
    [RecordStatus] => 26
)
[1] => Array(
    [RecordCount] => 2622
    [CardNumber] => 5786
    [RecordStatus] => 26
)
[2] => Array(
    [RecordCount] => 2874
    [CardNumber] => 6875
    [RecordStatus] => 26
)

2 个答案:

答案 0 :(得分:0)

您可以使用array_map

它将为数组中的每个元素调用一个函数。

在函数中,创建一个临时数组,该数组将保存不为空的值,并返回该临时数组作为该迭代的结果。

<?php

$arr = [
    [
        'RecordCount' => 1938,
        'CardNumber' => 4093,
        'CompanyID' => null,
        'RecordRequest' =>null,
        'RecordStatus' => 26
    ],
    [
        'RecordCount' => 2622,
        'CardNumber' => 5786,
        'CompanyID' =>null,
        'RecordRequest' =>null,
        'RecordStatus' => 26
    ],
    [
        'RecordCount' => 2874,
        'CardNumber' => 2874,
        'CompanyID' =>null,
        'RecordRequest' =>null,
        'RecordStatus' => 26    
    ]
];


$res = array_map(function($subarr) {
    $tmp = [];
    foreach($subarr as $key=>$val) {
        if(!empty($val)) {
            $tmp[$key] = $val;
        }
    }

    return $tmp;

},$arr);

var_dump($res);

答案 1 :(得分:0)

没有内置函数可以执行此操作,但这应该可以工作(ps!为php> = 7.1编写):

function remove_always_nulls(Iterable &$it)
{
    // dictionary of keys to keep (because they were non-null at some point)
    $keep_dict=array();
    $inner=function(Iterable $it)use(&$inner,&$keep_dict){
    foreach ($it as $key => $val) {
        if (is_iterable($val)) {
            $keep_dict[$key]=true;
            $inner($val);
        } elseif (!is_null($val)) {
            $keep_dict[$key]=true;
        }
    }
    };
    $inner($it);
    $remover=function(Iterable &$it_remove) use(&$remover,&$keep_dict){
        foreach($it_remove as $key=>&$val){
            if(is_iterable($val)){$remover($val);}elseif(!($keep_dict[$key]??false)){unset($it_remove[$key]);}
        }
    };
    $remover($it);
}