php 如何在跳过空数组项的同时内爆数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5985401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:06:04  来源:igfitidea点击:

How can I implode an array while skipping empty array items?

phpimplode

提问by Tom Auger

Perl's join()ignores (skips) empty array values; PHP's implode()does not appear to.

Perljoin()忽略(跳过)空数组值;PHP的implode()似乎没有。

Suppose I have an array:

假设我有一个数组:

$array = array('one', '', '', 'four', '', 'six');
implode('-', $array);

yields:

产量:

one---four--six

instead of (IMHO the preferable):

而不是(恕我直言更可取):

one-four-six

Any other built-ins with the behaviour I'm looking for? Or is it going to be a custom jobbie?

任何其他具有我正在寻找的行为的内置插件?或者它会成为一个定制的工作人员?

回答by Felix Kling

You can use array_filter():

您可以使用array_filter()

If no callbackis supplied, all entries of inputequal to FALSE(see converting to boolean) will be removed.

如果未提供回调,则所有等于的输入条目FALSE(请参阅转换为 boolean)将被删除。

implode('-', array_filter($array));

Obviously this will not work if you have 0(or any other value that evaluates to false) in your array and you want to keep it. But then you can provide your own callback function.

显然,如果您的数组中有0(或计算为 的任何其他值false)并且您想保留它,这将不起作用。但是你可以提供你自己的回调函数。

回答by Ben

I suppose you can't consider it built in (because the function is running with a user defined function), but you could always use array_filter.
Something like:

我想您不能认为它是内置的(因为该函数正在使用用户定义的函数运行),但您始终可以使用array_filter
就像是:

function rempty ($var)
{
    return !($var == "" || $var == null);
}
$string = implode('-',array_filter($array, 'rempty'));

回答by Thomas Hupkens

How you should implement you filter only depends on what you see as "empty".

您应该如何实施过滤器仅取决于您看到的“空”。

function my_filter($item)
{
    return !empty($item); // Will discard 0, 0.0, '0', '', NULL, array() of FALSE
    // Or...
    return !is_null($item); // Will only discard NULL
    // or...
    return $item != "" && $item !== NULL; // Discards empty strings and NULL
    // or... whatever test you feel like doing
}

function my_join($array)
{
    return implode('-',array_filter($array,"my_filter"));
} 

回答by Ali Varli

To remove null, false, emptystring but preserve 0, etc. use func. 'strlen'

要删除null, false,empty字符串但保留0等,请使用 func。' strlen'

$arr = [null, false, "", 0, "0", "1", "2", "false"];
print_r(array_filter($arr, 'strlen'));

will output:

将输出:

//Array ( [3] => 0 [4] => 0 [5] => 1 [6] => 2 [7] => false )

回答by ozzmotik

Based on what I can find, I'd say chances are, there isn't really any way to use a PHP built in for that. But you could probably do something along the lines of this:

根据我所能找到的,我想说的是,实际上没有任何方法可以使用内置的 PHP。但是您可能可以按照以下方式做一些事情:

function implode_skip_empty($glue,$arr) {
      $ret = "";
      $len = sizeof($arr);
      for($i=0;$i<$len;$i++) {
          $val = $arr[$i];    
          if($val == "") {
              continue;
          } else {
            $ret .= $arr.($i+1==$len)?"":$glue;
          }
      }
      return $ret;
}

回答by Jeremy

Try this:

尝试这个:

$result = array();

foreach($array as $row) { 
   if ($row != '') {
   array_push($result, $row); 
   }
}

implode('-', $result);

回答by cartbeforehorse

array_fileter()seems to be the accepted way here, and is probably still the most robust answer tbh.

array_fileter()似乎是这里公认的方式,并且可能仍然是最可靠的答案 tbh。

However, the following will also work if you can guarantee that the "glue" character doesn't already exist in the strings of each array element (which would be a given under most practical circumstances -- otherwise you wouldn't be able to distinguish the glue from the actual data in the array):

但是,如果您可以保证每个数组元素的字符串中不存在“胶水”字符(这在大多数实际情况下是给定的 - 否则您将无法区分)来自数组中实际数据的胶水):

$array = array('one', '', '', 'four', '', 'six');
$str   = implode('-', $array);
$str   = preg_replace ('/(-)+/', '', $str);

回答by user2775080

Try this:

尝试这个:

if(isset($array))  $array = implode(",", (array)$array);