2

I need to remove empty items in a multidimensional array. Is there a simple way I can remove the empty items easily? I need to keep only 2010-06 and 2010-07.

Thank you very much!

Array
(
    [2010-01] => Array
        (
            [2010-03] => Array
                (
                    [0] => 
                )
            [2010-04] => Array
                (
                    [0] => 
                )
            [2010-06] => Array
                (
                    [0] => stdClass Object
                        (
                            [data_test] => value
                            [date] => 2010-05-01 12:00:00
                        )

                )
            [2010-07] => Array
                (
                    [0] => stdClass Object
                        (
                            [data_test] => value
                            [date] => 2010-05-01 12:00:00
                        )

                )
        )
)
Igor O
  • 301
  • 1
  • 6
  • 26
  • 2
    Possible duplicate of [PHP: Remove empty array elements from a multidimensional array](http://stackoverflow.com/questions/9895130/php-remove-empty-array-elements-from-a-multidimensional-array) – Epodax Aug 25 '16 at 07:09
  • I tried this solution but it didn't work with this array. It has more levels. – Igor O Aug 25 '16 at 07:11
  • try using array_filter().. – Jaimin Aug 25 '16 at 07:13

2 Answers2

1

Try this Function. This will solve your issue.

 function cleanArray($array)
{
    if (is_array($array))
    {
        foreach ($array as $key => $sub_array)
        {
            $result = cleanArray($sub_array);
            if ($result === false)
            {
                unset($array[$key]);
            }
            else
            {
                $array[$key] = $result;
            }
        }
    }

    if (empty($array))
    {
        return false;
    }

    return $array;
}
Manish
  • 3,443
  • 1
  • 21
  • 24
0

array_filter will not wrok with this array so try this custom function

<?php
$array =array(
    20 => array(
        20 => array(
            0=> ''
        ),
        10 => array(
            0=> 'hey'
        )       

    )
);
function array_remove_empty($arr){
    $narr = array();
    while(list($key, $val) = each($arr)){
        if (is_array($val)){
            $val = array_remove_empty($val);
            // does the result array contain anything?
            if (count($val)!=0){
                // yes :-)
                $narr[$key] = $val;
            }
        }
        else {
            if (trim($val) != ""){
                $narr[$key] = $val;
            }
        }
    }
    unset($arr);
    return $narr;
}

print_r(array_remove_empty($array));
?> 

found this answer here

Mouner Mostafa
  • 132
  • 4
  • 18