简体   繁体   English

如何删除foreach循环内的数组元素?

[英]How can I delete array elements inside foreach loop?

I have a foreach loop and I would like to completely remove the array elements that satisfy the criteria, and change the keys to stay sequential 1,2,3,4. 我有一个foreach循环,我想完全删除满足条件的数组元素,并更改键以保持顺序1,2,3,4。

I have: 我有:

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

But this keeps the keys as they were before. 但这会保持键像以前一样。 I want to make them 1,2,3,4, how can this be achieved? 我想让它们成为1,2,3,4,这怎么实现?

Reset the array indices with array_values() : 使用array_values()重置数组索引:

$thearray = array_values( $thearray);
print_r($thearray);

You can just use array_filter to remove the array elements that satisfy the criteria 您可以只使用array_filter remove the array elements that satisfy the criteria

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

Then use array_values change the keys to stay 0, 1,2,3,4 .... as required 然后使用array_values根据需要将键更改为保持0、1、2、3、4 ....

  $thisarray = array_values($thisarray);

Build up a new array and then assign that to your original array after: 建立一个新数组,然后在执行以下操作后将其分配给您的原始数组:

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM