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

发布于 2024-11-07 02:24:24 字数 362 浏览 1 评论 0原文

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

假设我有一个数组:

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

yields:

one---four--six

而不是(恕我直言,更好):

one-four-six

任何其他具有我正在寻找的行为的内置函数?或者它会是一个定制的jobbie?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

如日中天 2024-11-14 02:24:24

您可以使用 array_filter()

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

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

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

You can use array_filter():

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

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.

鸠魁 2024-11-14 02:24:24

我想你不能认为它是内置的(因为该函数是使用用户定义的函数运行的),但你总是可以使用 array_filter
像这样的东西:

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

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:

function rempty ($var)
{
    return !($var == "" || $var == null);
}
$string = implode('-',array_filter($array, 'rempty'));
娇纵 2024-11-14 02:24:24

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

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

将输出:

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

To remove null, false, empty string but preserve 0, etc. use 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 )
各空 2024-11-14 02:24:24

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

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"));
} 

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"));
} 
小情绪 2024-11-14 02:24:24
$array = ["one", NULL, "two", NULL, "three"];
$string = implode("-", array_diff($array, [NULL]));
echo $string;

返回一二三

$array = ["one", NULL, "two", NULL, "three"];
$string = implode("-", array_diff($array, [NULL]));
echo $string;

Returns one-two-three

时间你老了 2024-11-14 02:24:24

根据我所能找到的,我想说的是,实际上没有任何方法可以使用内置的 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;
}

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:

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;
}
心碎无痕… 2024-11-14 02:24:24

试试这个:

$result = array();

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

implode('-', $result);

Try this:

$result = array();

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

implode('-', $result);
帥小哥 2024-11-14 02:24:24

不是直接答案,只是一般性提醒,您不必依赖单独的命名函数——您可以使用内联匿名函数来做到这一点,例如:

$imploded = implode("+", array_filter($array, function($chunk) {
        return (trim($chunk)!="");
    }));

Not a direct answer, but just a general reminder that you don't have to rely on a separate named function —— you can do this with an inline anonymous function such as:

$imploded = implode("+", array_filter($array, function($chunk) {
        return (trim($chunk)!="");
    }));
煮茶煮酒煮时光 2024-11-14 02:24:24

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

但是,如果您可以保证每个数组元素的字符串中不存在“粘合”字符(这在大多数实际情况下都是给定的),那么以下内容也将起作用 - 否则您将无法区分数组中实际数据的粘合):

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

array_fileter() seems to be the accepted way here, and is probably still the most robust answer 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 ('/(-)+/', '\1', $str);
囚我心虐我身 2024-11-14 02:24:24

试试这个:

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

Try this:

if(isset($array))  $array = implode(",", (array)$array);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文