2009-07-16 103 views

回答

4

你應該看看array_filter()。我認爲這正是你正在尋找的。

$_SESSION['items'] = array_filter($_POST['items']); 
+0

它沒有isset工作。驚人的一些PHP功能讓生活變得如此簡單。謝謝哥們! – payling 2009-07-16 19:08:21

3
# Cycle through each item in our array 
foreach ($_POST['items'] as $key => $value) { 
    # If the item is NOT empty 
    if (!empty($value)) 
    # Add our item into our SESSION array 
    $_SESSION['items'][$key] = $value; 
} 
0

像@Till Theis說,array_filter肯定是要走的路。您可以直接使用它,就像這樣:

$_SESSION['items'] = array_filter($_POST['items']); 

,這將給你這不評估,以虛假的陣列中的所有元素。 I.E.你會過濾掉兩個NULL,0,虛假等

你也可以傳遞一個回調函數來創建自定義篩選,就像這樣:

abstract class Util { 
    public static function filterNull ($value) { 
     return isset($value); 
    } 
} 

$_SESSION['items'] = array_filter($_POST['items'], array('Util', 'filterNull')); 

這將調用的Util類的filterNull法對於items-array中的每個元素,如果它們已設置(請參閱language construct isset()),則它們將保留在結果數組中。