html表格数组如何存储到php数组中不包含空元素
问题描述:
存储从表单提交的数组存储空元素元素。有没有办法只存储非空字段到PHP数组?html表格数组如何存储到php数组中不包含空元素
$ _SESSION ['items'] = $ _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