PHP:有条件地添加数组成员

时间:2010-01-04 20:16:31

标签: php arrays conditional

$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个不同的值,每个只设置如果每行上的变量都不为空,那么还有另一种方法设置一个条件 - 在一个数组声明?如果没有,那么解决这个问题的另一种方法是什么?

谢谢!

3 个答案:

答案 0 :(得分:2)

遍历您的选项数组,如果该值不为空,请将其添加到标题数组中:

$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
  }
}

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

你不能在数组子句中做任何可以帮助你的条件,但这应该适合你的需要:

如果要传递给数组的标题如下:

$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: */*'
           );