需要帮助从多维数组中删除空数组值

时间:2011-06-30 00:16:41

标签: php multidimensional-array

我想知道是否有人可以帮助我,我有一个多维数组,如果它们是空的,我需要删除它们(好吧,设置为0)。这是我的数组:

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

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

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

)

我只想留下:

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

)

如果有人能帮助我,那太棒了! :)

2 个答案:

答案 0 :(得分:1)

这将对您有所帮助:

Remove empty items from a multidimensional array in PHP

修改

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

答案 1 :(得分:1)

看起来你需要树遍历:

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