0

我有一个 foreach 循环,我想完全删除满足条件的数组元素,并更改键以保持顺序 1、2、3、4。

我有:

$thearray = array(20,1,15,12,3,6,93);
foreach($thearray as $key => $value){
    if($value < 10){
        unset($thearray[$key]);
    }
}
print_r($thearray);

但这会使密钥保持原样。我想让它们成为1,2,3,4,如何实现?

4

3 回答 3

5

重置数组索引array_values()

$thearray = array_values( $thearray);
print_r($thearray);
于 2012-11-02T16:48:30.387 回答
1

你可以array_filterremove the array elements that satisfy the criteria

 $thisarray = array_filter($thearray,function($v){ return $v > 10 ;});

然后根据array_values需要使用更改键保持 0, 1,2,3,4 ....

  $thisarray = array_values($thisarray);
于 2012-11-02T16:46:22.203 回答
0

建立一个新数组,然后将其分配给您的原始数组:

$thearray=array(20,1,15,12,3,6,93);
$newarray=array();
foreach($thearray as $key=>$value){
  if($value>=10){
    $newarray[]=$value
  }
}
$thearray=$newarray;
print_r($thearray);
于 2012-11-02T16:47:57.313 回答