2014-03-13 61 views
0

這是我在print_r我的數組時獲得的結果。它是一個包含以下值的多維數組。如果數組值等於0,則刪除條目

[7] => Array 
    (
     [0] => 1 
     [1] => 34 
     [2] => 181 
     [3] => 50 
    ) 



    [9] => Array 
    (
     [0] => 1 
     [1] => 2 
     [2] => 1 
     [3] => 47 
    ) 

    [2] => Array 
    (
     [0] => 20 
     [1] => 0 
     [2] => 1621 
     [3] => 45 
    ) 
    [3] => Array 
    (
     [0] => 120 
     [1] => 0 
     [2] => 121 
     [3] => 45 
    ) 

我想刪除其中的關鍵[1]等於0做修改後的所有條目,我的最後一個數組應該喜歡這個

[7] => Array 
    (
     [0] => 1 
     [1] => 34 
     [2] => 181 
     [3] => 50 
    ) 



[9] => Array 
    (
     [0] => 1 
     [1] => 2 
     [2] => 1 
     [3] => 47 
    ) 

任何想法?

回答

3

foreach救援:

foreach($arr as $key => $entry) { 
    if(isset($entry[1]) && $entry[1] === 0) { 
     unset($arr[$key]); 
    } 
} 

而一個array_filter例如:

$arr = array_filter($arr, function($entry) { 
    return $entry[1] !== 0; 
}); 

(假設至少PHP 5.3,雖然你可以通過創建一個命名函數,並將其作爲繞開這個問題第二個參數爲array_filter

+0

快速,乾淨。非常感謝 – user3172841

1

如果您只想移除數組值爲0的數組,那麼您可以使用array_filter

<?php 

    $array = array(1,2,3,4,5,0,'',null); 

    print_r(array_filter($array)); 
    ?> 

輸出:

Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5) 
0

可以使用這個代碼

代碼刪除數組爲空,null,並且0值: -

$array = array('one', 'two', '', 'three', null,'four','0'); 

$filteredarray = array_values(array_filter($array)); 

print_r($filteredarray); 

輸出: -

Array 
(
    [0] => one 
    [1] => two 
    [2] => three 
    [3] => four 
) 

謝謝!祝一切順利!!

相關問題