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
                        )

                )
        )
)
3
  • 2
    Possible duplicate of PHP: Remove empty array elements from a multidimensional array Commented Aug 25, 2016 at 7:09
  • I tried this solution but it didn't work with this array. It has more levels. Commented Aug 25, 2016 at 7:11
  • try using array_filter().. Commented Aug 25, 2016 at 7:13

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.