开发者

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
            [uni开发者_Python百科ts] => 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! :)


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜