Igor O
Igor O

Reputation: 301

Remove items from multidimensional array in PHP

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
                        )

                )
        )
)

Upvotes: 2

Views: 238

Answers (2)

Mouner Mostafa
Mouner Mostafa

Reputation: 142

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

Upvotes: 0

Manish
Manish

Reputation: 3643

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;
}

Upvotes: 1

Related Questions