SoulieBaby
SoulieBaby

Reputation: 5471

Need help with removing empty array values from a multidimensional array

I was wondering if anyone could help me out, I have a multidimensional array and I need the values removed if they're empty (well, set to 0). Here's my array:

Array
(
    [83] => Array
        (
            [ctns] => 0
            [units] => 1
        )

    [244] => Array
        (
            [ctns] => 0
            [units] => 0
        )

    [594] => Array
        (
            [ctns] => 0
        )

)

And I want to only be left with:

Array
(
    [83] => Array
        (
            [units] => 1
        )

)

If anyone could help me, that would be fantastic! :)

Upvotes: 0

Views: 411

Answers (2)

cwallenpoole
cwallenpoole

Reputation: 82028

Looks like you need tree traversal:

function remove_empties( array &$arr )
{
    $removals = array();
    foreach( $arr as $key => &$value )
    {
         if( is_array( $value ) )
         {
              remove_empties( $value ); // SICP would be so proud!
              if( !count( $value ) ) $removals[] = $key;
         }
         elseif( !$value ) $removals[] = $key;
    }
    foreach( $removals as $remove )
    {
        unset( $arr[ $remove ] );
    }
}

Upvotes: 1

Sascha Galley
Sascha Galley

Reputation: 16091

this will help you:

Remove empty items from a multidimensional array in PHP

Edit:

  function array_non_empty_items($input) {
     // If it is an element, then just return it
     if (!is_array($input)) {
       return $input;
     }


    $non_empty_items = array();

    foreach ($input as $key => $value) {
       // Ignore empty cells
       if($value) {
         // Use recursion to evaluate cells 
         $items = array_non_empty_items($value);
         if($items)
             $non_empty_items[$key] = $items;
       }
     }

    // Finally return the array without empty items
     if (count($non_empty_items) > 0)
         return $non_empty_items;
     else
         return false;
   }

Upvotes: 1

Related Questions