仅当非空或 null 时才输出数组的值

Output values of the array only if not empty or null

我真的是 php 的新手,不知道我应该查找什么来解决这个问题。如果变量不为空也不为空,我将尝试仅显示值。

在我分配的数组中:

$attributes [
    'glutenfree'     => getPublicClassificationsDescription($classifications, ARTICLE_GLUTENFREE),
    'lactosefree'    => getPublicClassificationsDescription($classifications, ARTICLE_LACTOSEFREE),
    'flavouringfree' => getPublicClassificationsDescription($classifications, ARTICLE_FLAVOURINGFREE),
    'corerange'      => getPublicClassificationsDescription($classifications, ARTICLE_CORERANGE),
    'engro'          => getPublicClassificationsDescription($classifications, ARTICLE_ENGRO),
    'vegan'          => getPublicClassificationsDescription($classifications, ARTICLE_VEGAN),
...
];

还有很多其他的属性。 我想要输出,如果它不为空也不为空,它只打印到 CSV。

现在我得到这样的结果:

glutenfree=,lactosefree=,flavouringfree=,corerange=,engro=,vegan=No,...

我需要的输出就像 empty/null 的所有内容都应该消失,但有价值的应该在那里。在这个例子中:

vegan=No,...

例如,如果我尝试使用 "empty" 或 "isset" 它不起作用,我得到一个没有错误的空白页面。

$glutenfree = getPublicClassificationsDescription($classifications, ARTICLE_GLUTENFREE);

$attributes [
    if (!empty($glutenfree)) {
        'glutenfree'     => $glutenfree,
        'lactosefree'    => getPublicClassificationsDescription($classifications, ARTICLE_LACTOSEFREE),
        'flavouringfree' => getPublicClassificationsDescription($classifications, ARTICLE_FLAVOURINGFREE),
        'corerange'      => getPublicClassificationsDescription($classifications, ARTICLE_CORERANGE),
        'engro'          => getPublicClassificationsDescription($classifications, ARTICLE_ENGRO),
        'vegan'          => getPublicClassificationsDescription($classifications, ARTICLE_VEGAN),
        ...
    }
];

在将数据推送到数组之前,您需要检查变量是否为空,如下所示:

#first, create an empty array
$attributes = array();
#get lactose value
$lactose_value = getPublicClassificationsDescription($classifications, ARTICLE_LACTOSEFREE);
#check if not empty string
if ($lactose_value !='') {
  #pushing to array
  $attributes['lactosefree'] = $lactose_value;
}

可以使用 foreach 指令改进此例程。

$attributes = array()
#all fields now are inside an array
$fields = [ARTICLE_GLUTENFREE=>'glutenfree', ARTICLE_LACTOSEFREE=>'lactosefree',
          ARTICLE_FLAVOURINGFREE=>'flavouringfree', ARTICLE_CORERANGE=>'corerange' ,
          ARTICLE_ENGRO=>'engro', ARTICLE_VEGAN=>'vegan' ];
#iterating
$foreach($fields as $key=>$field) {
  #getting the value
  $arr_value = getPublicClassificationsDescription($classifications, $key);
  #check if not empty string
  if ($arr_value !='') {
    $attributes[$field] = $arr_value;
  }
}

感谢 Dont Panic 的贡献。 感谢 mickmackusa 的修改。

最简单的解决方案(最简单的是对现有代码进行最少的修改)就是这样做

$attributes = array_filter($attributes);

在将数组转换为字符串之前。