【问题标题】:Can't remove empty elements from array无法从数组中删除空元素
【发布时间】:2011-04-08 18:58:40
【问题描述】:

我想从数组中删除空元素。我有一个由explode() 设置为数组的$_POST-String。然后我使用循环来删除空元素。但这不起作用。我也尝试了array_filter(),但没有成功。你能帮助我吗?请参阅下面的代码:

$cluster = explode("\n", $_POST[$nr]);

     print_r ($cluster);
     echo "<br>";

  for ($i=0 ; $i<=count($cluster);$i++) 
    {
      if ($cluster[$i] == '') 
       {
         unset ( $cluster[$i] );
       }
    }

     print_r ($cluster);
     echo "<br>";

结果:

Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => [5] => )

Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => ) 

【问题讨论】:

  • 我们无法真正看到你的空元素是什么

标签: php arrays


【解决方案1】:

使用array_filter 可以轻松删除空元素:

$array = array_filter($array);

例子:

$array = array('item_1' => 'hello', 'item_2' => '', 'item_3' => 'world', 'item_4' => '');
$array = array_filter($array);
/*
Array
(
    [item_1] => hello
    [item_3] => world
)
*/

【讨论】:

【解决方案2】:

问题在于每次运行时都会评估 for 循环条件。

这意味着count(...) 将被多次调用,并且每次数组缩小时。

正确的做法是:

$test = explode("/","this/is/example///");
print_r($test);
$arrayElements = count($test);
for($i=0;$i<$arrayElements;$i++)
    if(empty($test[$i])
        unset($test[$i]);

print_r($test);

没有额外变量的另一种方法是倒数:

$test = explode("/","this/is/example///");
print_r($test);
for($i=count($test)-1;$i>=0;$i--)
    if(empty($test[$i])
        unset($test[$i]);

print_r($test);

【讨论】:

  • 谢谢。我现在用 trim & a while loop $i = 0; 解决了这个问题。 $v = 计数($cluster); while ( $i
【解决方案3】:

如果你改变了怎么办:

for ($i=0 ; $i<=count($cluster);$i++) { if ($cluster[$i] == '') { unset ( $cluster[$i] ); } }

for ($i=0 ; $i<=count($cluster);$i++) { if (trim($cluster[$i]) == '') { unset ( $cluster[$i] ); } }

【讨论】:

  • 太棒了。感谢您的快速答复!
  • 结果是这样的:Array ([0] => Test1 [1] => Test2 [2] => [3] => [4] => [5] => )
    数组 ( [0] => Test1 [1] => Test2 [5] => )
猜你喜欢
  • 2018-08-29
  • 1970-01-01
  • 2018-08-06
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 2023-03-09
相关资源
最近更新 更多