从数组中删除空值

时间:2013-03-12 13:14:51

标签: php arrays

我有一个数组,我使用DOM从html中提取。现在,如下面的数组所示,有许多我不想要的空数据。所以,每当我尝试从数组中删除未删除的空值时。

Array ( [0] => [1] => Outpost Congratulations13 [2] => [3] => [4] => [5] => [6] =>
 [7] => Yard will reflect the type of work that they do and the strength and variety of their membership, from recent graduates to emerging and mid-career artists. 
[8] => [9] => [10] => [11] => Gallery  Closed Good Friday, open Bank Holiday Monday. Admission Free 
[12] => [13] => K  Yard, Castle Street 
[14] => [15] => Friday 1 Mar 3 [16] => [17] => [18] => [19] => www.somesite.co.uk 
[20] => [21] => [22] => [23] => Map [24] => [25] => Contact the Organiser Tell a Friend about this Event [26] => [27] => Plan Your Journey [28] => [29] => [30] => )

我所做的一切: -

  1. array_filter:它没有用。
  2. 检查值是否为空的许多函数仍然无效。
  3. 我尝试使用strlen来查找空字符串的长度,但它显示22,230作为长度。
  4. 我使用str_replace用ntg替换空格仍然没有工作,而stlen显示空值为22,28等。
  5. 我用过修剪bt没用...
  6. 任何人都可以帮我解释为什么数据的strlen为22或更多。以及如何从数组中删除这些类型的元素

3 个答案:

答案 0 :(得分:3)

这应该做你需要的:

$array = array(
  'Hello',
  '',
  0,
  NULL,
  FALSE,
  '0',
  '    ',
);

$new_array = array_filter($array, function ($value)
{
    return strlen(trim($value));
}
);

这将给出:

Array ( [0] => Hello [2] => 0 [5] => 0 )

使用array_filter($array)array_filter($array, 'trim')的问题是字符串/整数0也会被删除,这可能不是您想要的?

编辑:

如果你正在使用PHP< 5.3,使用以下内容:

function trim_array ($value)
{
    return strlen(trim($value));
}

$new_array = array_filter($array, 'trim_array');

答案 1 :(得分:3)

由于数据有空字符串(22个空格等),我们需要修剪它们

$emptyRemoved = array_filter($myArray, 'trim');

答案 2 :(得分:0)

function array_remove_empty($arr){
    $narr = array();
    while(list($key, $val) = each($arr)){
        if (is_array($val)){
            $val = array_remove_empty($val);
            // does the result array contain anything?
            if (count($val)!=0){
                // yes :)
                $narr[$key] = $val;
            }
        }
        else {
            if (trim($val) != ""){
                $narr[$key] = $val;
            }
        }
    }
    unset($arr);
    return $narr;
}

array_remove_empty(array(1,2,3, '', array(), 4)) => returns array(1,2,3,4)