【发布时间】:2009-07-17 03:11:40
【问题描述】:
存储从表单提交的数组存储具有空值的元素。有没有办法只将非空字段存储到 php 数组中?
$_SESSION['items'] = $_POST['items'];
是我当前的代码。
【问题讨论】:
存储从表单提交的数组存储具有空值的元素。有没有办法只将非空字段存储到 php 数组中?
$_SESSION['items'] = $_POST['items'];
是我当前的代码。
【问题讨论】:
你应该看看array_filter()。我认为这正是您正在寻找的。p>
$_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']);
这将为您提供数组中 not 评估为 false 的所有元素。 IE。您将过滤掉 NULL、0、false 等。
您还可以传递回调函数来创建自定义过滤,如下所示:
abstract class Util {
public static function filterNull ($value) {
return isset($value);
}
}
$_SESSION['items'] = array_filter($_POST['items'], array('Util', 'filterNull'));
这将为 items-array 中的每个元素调用 Util 类的 filterNull 方法,如果设置了它们(请参阅language construct isset()),那么它们将保留在结果数组中。
【讨论】: