[英]How can I delete array elements inside foreach loop?
我有一个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,这怎么实现?
使用array_values()
重置数组索引:
$thearray = array_values( $thearray);
print_r($thearray);
您可以只使用array_filter
remove 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);
建立一个新数组,然后在执行以下操作后将其分配给您的原始数组:
$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.