【问题标题】:PHP: Conditionally add array membersPHP:有条件地添加数组成员
【发布时间】:2011-01-01 09:30:20
【问题描述】:
$headers=array(
     $requestMethod." /rest/obj HTTP/1.1",
     "listable-meta: ".$listablemeta,
     "meta: ".$nonlistmeta,
     'accept: */*',
      );

在上面的示例中,如果 $listablemeta 或 $nonlistmeta 为空,我想省略整行。 假设 $listablemeta 是空白的。那么数组将是:

$headers=array(
     $requestMethod." /rest/obj HTTP/1.1",
     "meta: ".$nonlistmeta,
     'accept: */*',
      );

现在我可以设置一个条件 isempty() 并相应地设置数组,但是如果我想构造一个具有 20 个不同值的数组,每个值仅在每行上的变量不为空的情况下设置,还有另一种方法吗?在数组声明中设置条件?如果不是,还有什么方法可以解决这个问题?

谢谢!

【问题讨论】:

    标签: php arrays conditional


    【解决方案1】:

    遍历你的 options 数组,如果值不为空,将它添加到你的 headers 数组中:

    $headers = array(
      $requestMethod." /rest/obj HTTP/1.1",
      "meta: ".$nonlistmeta,
      'accept: */*'
    );
    
    $items = array(
      "item1" => "",
      "item2" => "foo"
    );
    
    foreach ($items as $key => $val) {
      if ($val != "") {
        $headers[] = $val; // only 'foo' will be passed
      }
    }
    

    【讨论】:

    • 没有抓住重点,应该过滤的是$headers数组;如果$nonlistmeta 为空,则应从$headers 中删除该行。您的示例只是将新项目添加到数组中,甚至不会以 key: value 的形式出现。
    【解决方案2】:

    我不知道如何在声明中这样做,但一个简单的辅助函数可能会解决问题:

    function array_not_empty($values){
      $array = array();
      foreach($values as $key=>$value){
        if(!empty($value)) $array[$key] = $value;
      }
      return $array;
    }
    

    【讨论】:

      【解决方案3】:

      您不能在数组子句中执行任何可以帮助您解决此问题的条件,但这应该适合您的需求:

      如果要传递给数组的headers如下:

      $requestMethod = 'GET';
      $listablemeta = ''; // This shouldn't be in the final result
      $nonlistmeta = 'non-listable-meta';
      

      构建这些变量的键/值数组:

      $headers = array(
                     0 => $requestMethod." /rest/obj HTTP/1.1",
                     'listable-meta' => $listablemeta,
                     'meta' => $nonlistmeta,
                     'accept', '*/*'
                 );
      

      请注意,如果该值没有 requestMethod 中的键,则只需在其中输入一个数值。然后循环它们并构建最终的数组:

      function buildHeaders($headers) {
          $new = array();
      
          foreach($headers as $key => $value) {
              // If value is empty, skip it
              if(empty($value)) continue;
              // If the key is numerical, don't print it
              $new[] = (is_numeric($key) ? '' : $key.': ').$value;
          }
      
          return $new;
      }
      
      $headers = buildHeaders($headers);
      

      $headers 现在应该包含如下内容:

      $headers = array(
                     'GET /rest/obj HTTP/1.1',
                     'meta: non-listable-meta-here',
                     'accept: */*'
                 );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        • 1970-01-01
        相关资源
        最近更新 更多