存儲從表單提交的數組存儲空元素元素。有沒有辦法只存儲非空字段到PHP數組?html表格數組如何存儲到php數組中不包含空元素
$ _SESSION ['items'] = $ _POST ['items'];
是我當前的代碼。
存儲從表單提交的數組存儲空元素元素。有沒有辦法只存儲非空字段到PHP數組?html表格數組如何存儲到php數組中不包含空元素
$ _SESSION ['items'] = $ _POST ['items'];
是我當前的代碼。
你應該看看array_filter()。我認爲這正是你正在尋找的。
$_SESSION['items'] = array_filter($_POST['items']);
# 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;
}
像@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()),則它們將保留在結果數組中。
它沒有isset工作。驚人的一些PHP功能讓生活變得如此簡單。謝謝哥們! – payling 2009-07-16 19:08:21