2011-06-30 147 views
0

我想知道是否有人可以幫助我,我有一個多維數組,我需要刪除的值,如果他們是空的(以及設置爲0)。這裏是我的數組:需要幫助,從多維數組中刪除空陣列值

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

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

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

) 

我想只留下了:

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

) 

如果有人可以幫助我,那將是非常美妙! :)

回答

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

星爺我試過一個,但它並不像我需要它的工作方式那樣工作。例如。 Array([244] => Array()) – SoulieBaby

+1

@SoulieBaby編輯源代碼以符合您的要求...沒有測試它,但應該可以幫助您找到解決方案 –

+0

非常感謝:)非常棒! – SoulieBaby

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