【问题标题】:html form arrays how to store into php array not including null elementshtml表单数组如何存储到不包括空元素的php数组中
【发布时间】:2009-07-17 03:11:40
【问题描述】:

存储从表单提交的数组存储具有空值的元素。有没有办法只将非空字段存储到 php 数组中?

$_SESSION['items'] = $_POST['items'];

是我当前的代码。

【问题讨论】:

    标签: php html


    【解决方案1】:

    你应该看看array_filter()。我认为这正是您正在寻找的。​​p>

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

    【讨论】:

    • 它在没有 isset 的情况下工作。惊人的一些 php 函数让生活变得如此简单。谢谢哥们!
    • 对,我忘记了自动转换以及空表单值不是 NULL 而是空字符串这一事实。
    【解决方案2】:
    # 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;
    }
    

    【讨论】:

      【解决方案3】:

      就像@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()),那么它们将保留在结果数组中。

      【讨论】:

        猜你喜欢
        • 2022-10-13
        • 1970-01-01
        • 2021-10-10
        • 1970-01-01
        • 2018-04-06
        • 2017-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多