0

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! :)

2 Answers 2

1

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

2 Comments

Yeh I tried that one, but it doesn't quite work the way I need it to work. Eg. Array ( [244] => Array () )
@SoulieBaby edited the source code to fit your requirements...didn't test it but should help you find the solution
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.