使用PHP删除具有空子数组的多维数组

时间:2019-01-18 11:17:01

标签: php arrays multidimensional-array

我有这个数组如下。每个学生从星期一到星期日都有7个阵列,每个内部阵列都有一天的活动

$array = [
    'Alex' => [
        [
            ['event' => 'eventName1'],['event' => 'eventName2']
        ],
        [
            ['event' => 'eventName3'],['event' => 'eventName4']
        ],
        [
            ['event' => 'eventName5'],['event' => 'eventName6']
        ],
        [
            ['event' => 'eventName7'],['event' => 'eventName8']
        ],
        [],
        [],
        []

    ], 
 'christoper'=>[
      [],[],[],[],[],[],[]
 ]
];

输出数组应为

[
    'Alex' => [
        [
            ['event' => 'eventName1'],['event' => 'eventName2']
        ],
        [
            ['event' => 'eventName3'],['event' => 'eventName4']
        ],
        [
            ['event' => 'eventName5'],['event' => 'eventName6']
        ],
        [
            ['event' => 'eventName7'],['event' => 'eventName8']
        ],
        [],
        [],
        []

    ]
];

我已经尝试过了

$array = array_filter(array_map('array_filter', $array));

但是结果是徒劳的。谁能帮助我获得所需的输出。我想过滤掉没有活动的学生

3 个答案:

答案 0 :(得分:2)

您可以这样做:

<?php

$output = array_filter($array, function (array $studentDays) {
    foreach ($studentDays as $day) {
        // if there is a *non-empty* day, we return early and keep the whole record
        if (! empty($day)) {
            return true;
        }
    }

    // only empty days, so discard the record
    return false;
});

https://3v4l.org/AkshS

答案 1 :(得分:0)

遍历数组并应用rm(list=ls(all=TRUE)) library(tmap) data(World, metro) # put population size pop2020 to NA for some cities metro$pop2020[10:300] <- NA # add column with code for the shape of the symbol (21 for data available, 4 for NA) metro$shape_symbol <- 21 metro[is.na(metro$pop2020), ]$shape_symbol <- 4 tm_shape(World) + tm_fill()+ tm_shape(metro) + tm_symbols( size = "pop2020", col = "black", shape = "shape_symbol", # use column shape_symbol in metro for the symbol # shapeNA = "4", # should plot NA as cross by default - didn´t work for me title.size = "subtitle", legend.size.is.portrait=TRUE) + tm_layout(legend.bg.color = "gray", legend.frame = "black")

array_filter

答案 2 :(得分:0)

array_filter的递归调用将完成此工作;在外部调用中,我们检查返回数组的大小,以决定是否保留该元素(如果数组仅由空数组组成,则为0,就像对“ christopher”所做的那样):

$array = array_filter($array, function ($v) { return count(array_filter($v)); });

Demo on 3v4l.org