1

我想删除数组中的空值并删除仅包含一个单词的值。

这是我的代码:

$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 />";
    }
}

我想删除空值和单词“猪”,帮助我使这段代码工作。谢谢你。

4

5 回答 5

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);
});
于 2012-12-05T10:47:15.133 回答
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 删除空值作为评估为假。

另一种方式:

<?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 );
于 2012-12-05T10:39:29.993 回答
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);

以上回声:

数组(3){[0]=>字符串(10)“聪明的狮子”[1]=>字符串(11)“聪明的鸭子”[2]=>字符串(10)“小蚂蚁”}

于 2012-12-05T10:51:47.480 回答
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";
}

http://codepad.org/j6B2eEEX

于 2012-12-05T10:40:04.420 回答
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;
    }
}
于 2012-12-05T10:42:17.830 回答