如何从PHP中的多维数组中删除空值? [英] How to remove empty values from multidimensional array in PHP?

查看:116
本文介绍了如何从PHP中的多维数组中删除空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找很多答案,但是没有一个对我有用.

I've been looking a lot of answers, but none of them are working for me.

这是分配给我的$quantities数组的数据:

This is the data assigned to my $quantities array:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array([35.00] => )
    [1] => Array([30.00] => )
    [2] => Array([30.00] => )
)

我正在寻找一种方法来删除具有空值(如[12] [1][2])的子数组,同时保留所有其他内容.

I'm looking for a way to remove the subarrays with empty values like [12] [1] and [2] while keeping everything else.

所需结果:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
)

我在官方php文档上尝试了很多功能,但没有一个起作用.

I tried a lot of the functions on the official php docs and none of them worked.

我用过这个:

function array_filter_recursive($array, $callback = null) {
    foreach ($array as $key => & $value) {
        if (is_array($value)) {
            $value = array_filter_recursive($value, $callback);
        } else {
            if ( ! is_null($callback)) {
                if ( ! $callback($value)) {
                    unset($array[$key]);
                }
            } else {
                if ( ! (bool) $value) {
                    unset($array[$key]);
                }
            }
        }
    }
    unset($value);
    return $array;
}

但是它只会删除子数组中的元素;我需要将子数组完全删除.

But it only removes the element in the subarrays; I need the subarrays to be removed entirely.

我不想要这个:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array()
    [1] => Array()
    [2] => Array()
)

推荐答案

有点晚,但可能会帮助寻找相同答案的人.我使用了这种非常简单的方法;

Bit late, but may help someone looking for same answer. I used this very simple approach to;

  1. 从嵌套数组中删除所有不包含任何值的键,然后
  2. 删除所有空的嵌套数组.


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

这篇关于如何从PHP中的多维数组中删除空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆