阵列的输出值仅如果不为空或空

问题描述 投票:0回答:2

我真的很新的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,...

我需要的输出就像是空/空应该走了,但与价值的人应该在那里的一切。在这个例子:

vegan=No,...

例如,如果我尝试用“空”或“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),
        ...
    }
];
php arrays if-statement isset is-empty
2个回答
0
投票

最简单的办法(最简单的在现有代码的最小修改)将只是做

$attributes = array_filter($attributes);

你的数组转换为字符串之前。


0
投票

你需要检查,如果变量是将数据推送到阵列,这样的前空:

#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为您的修正。

© www.soinside.com 2019 - 2024. All rights reserved.