我想删除数组中的空值并删除只包含一个单词的值。
这是我的代码:
$all = "smart lion, smart duck, small ant, , pig";
$allkey = explode (',',$all);
$allkey = array_unique($allkey);
for ($i = 0; $i < (count($allkey)); $i++)
{
if (str_word_count($allkey[$i]) < 2)
{
unset($allkey[$i]);
}
else
{
echo $allkey[$i]."<br />";
}
}
我想删除空值和单词&#34; pig&#34;, 帮助我使这段代码工作。 谢谢。
答案 0 :(得分:0)
<?php
$all = "smart lion, smart duck, small ant, , pig";
$allkey = explode (',',$all);
$allkey = array_unique($allkey);
$allkey = array_map( 'trim', $allkey );
$allkey = array_filter( $allkey );
var_dump( $allkey );
array_map遍历您的数组并执行函数trim,它将删除开始和尾随空格。 array_filter将空值删除为evaluate。
其他方式:
<?php
$all = "smart lion, smart duck, small ant, , pig";
$allkey = explode (',',$all);
$allkey = array_unique($allkey);
foreach( $allkey as $key => $entry ) {
$entry = trim( $entry );
if( empty($entry) ) {
unset( $allkey[$key] );
}
}
var_dump( $allkey );
答案 1 :(得分:0)
有代码
$all = "smart lion, smart duck, small ant, , pig, pelican";
$allkey = explode (',',$all);
$allkey = array_unique($allkey);
for ($i = 0; $i < (count($allkey)); $i++)
{
//we count the number of words
$allwords = explode (' ',$allkey[$i]);
//Remove empty words
for ($j = 0; $j < (count($allwords)); $j++) {
if ($allwords[$j]=="") unset($allwords[$j]);
}
if (count($allwords)<2)
unset($allkey[$i]);
else
echo trim($allkey[$i])."\n";
}
答案 2 :(得分:0)
首先,我希望trim()
在循环内部像
for ($i = 0; $i < (count($allkey)); $i++)
{
$elem = trim($allkey[$i]);
}
其次,要跳过少于两个单词的值,我会将其写入一个单独的数组中。所以在for(...)
循环之前添加:
$foundelems = array();
然后在for(...)
循环内,执行if
:
if(str_word_count($elem) >= 2) {
$foundelems[] = $elem;
}
您在$foundelems
数组中拥有正确的项目。一起来:
$all = "smart lion, smart duck, small ant, , pig";
$allkey = explode (',',$all);
$allkey = array_unique($allkey);
$foundelems = array();
for ($i = 0; $i < (count($allkey)); $i++)
{
$elem = trim($allkey[$i]);
if(str_word_count($elem) >= 2) {
$foundelems[] = $elem;
}
}
答案 3 :(得分:0)
使用自定义回调函数,只需调用array_filter即可实现您想要的效果:
$all = "smart lion, smart duck, small ant, , pig";
// get array of unique, trimmed elements
$exploded = array_unique(array_map('trim', explode(',', $all)));
$allkey = array_filter($exploded, function($el) {
$val = trim($el);
// return false if empty or only one word, which will remove the element from the array
return (!empty($val) && str_word_count($val) >= 2);
});
答案 4 :(得分:0)
您可以执行以下操作:
$arr = explode(',',"smart lion, smart duck, small ant, , pig");
foreach($arr as $ky => $val) {
if (strpos(trim($val),' ') === false) {
unset($arr[$ky]);
}
}
var_dump($arr);
以上回音:
array(3){[0] =&gt; string(10)“smart lion”[1] =&gt; string(11)“聪明 duck“[2] =&gt; string(10)”small ant“}