-1

我有一个看起来像这样的数组

 $hours_worked = array('23',0,'24',0)

想要做的是遍历数组并删除包含0的元素

到目前为止,我所拥有的是:

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

但是我得到的结果是$hours_worked = array(23,24,0). 即它不会从数组中删除最后一个元素。有任何想法吗?

4

2 回答 2

0

这段代码的问题是你count($hours_worked)每次迭代都在计算;一旦你删除了一个项目,计数就会减少,这意味着对于每个删除的项目,循环将在看到数组末尾的一个项目之前终止。因此,解决它的直接方法是将计数拉出循环:

$count = count($hours_worked);
for($i = 0; $i < $count; $i++) {
   // ...
}

That said, the code can be further improved. For one you should always use foreach instead of for -- this makes the code work on all arrays instead of just numerically indexed ones, and is also immune to counting problems:

foreach ($hours_worked as $key => $value) {
    if ($value === 0) unset($hours_worked[$key]);
}

You might also want to use array_diff for this kind of work because it's an easy one-liner:

$hours_worked = array('23',0,'24',0);
$hours_worked = array_diff($hours_worked, array(0)); // removes the zeroes

If you choose to do this, be aware of how array_diff compares items:

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

于 2013-03-13T21:26:08.120 回答
-1

尝试使用 foreach 循环

$new_array = array();
foreach($hours_worked as $hour) {
   if($hour != '0') {
      $new_array[] = $hour;
   }
}
// $new_array should contain array(23, 24)
于 2013-03-13T21:21:49.557 回答