如何在跳过空数组项的同时内爆数组?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您可以使用
array_filter()
:显然,如果您的数组中有
0
(或任何其他计算结果为false
的值)并且您想保留它,那么这将不起作用。但随后您可以提供自己的回调函数。You can use
array_filter()
:Obviously this will not work if you have
0
(or any other value that evaluates tofalse
) in your array and you want to keep it. But then you can provide your own callback function.我想你不能认为它是内置的(因为该函数是使用用户定义的函数运行的),但你总是可以使用 array_filter。
像这样的东西:
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:
要删除
null
、false
、empty
字符串但保留0
等,请使用 func。 'strlen
'将输出:
To remove
null
,false
,empty
string but preserve0
, etc. use func. 'strlen
'will output:
您应该如何实现过滤器仅取决于您所看到的“空”。
How you should implement you filter only depends on what you see as "empty".
返回
一二三
Returns
one-two-three
根据我所能找到的,我想说的是,实际上没有任何方法可以使用内置的 PHP 来实现这一点。但你可能可以这样做:
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:
试试这个:
Try this:
不是直接答案,只是一般性提醒,您不必依赖单独的命名函数——您可以使用内联匿名函数来做到这一点,例如:
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:
array_fileter() 似乎是这里可接受的方式,并且可能仍然是最可靠的答案。
但是,如果您可以保证每个数组元素的字符串中不存在“粘合”字符(这在大多数实际情况下都是给定的),那么以下内容也将起作用 - 否则您将无法区分数组中实际数据的粘合):
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):
试试这个:
Try this: