Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty values from multidimensional array in PHP?

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

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] => )
)

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

The desired result:

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

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

I've used this one:

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.

I don't want this:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array()
    [1] => Array()
    [2] => Array()
)
like image 664
Richard-MX Avatar asked Apr 18 '12 17:04

Richard-MX


1 Answers

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

  1. remove all the keys from nested arrays that contain no value, then
  2. remove all the empty nested arrays.

$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );
like image 197
Alastair F Avatar answered Oct 28 '22 08:10

Alastair F