2012-11-02 89 views
0

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

我:

$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,这怎么能实现?

+0

这使我:阵列([0] => 20 [2] => 15 [3] => 12 [6] => 93)但是,我想要的键是0,1,2,3不是0,2,3,6 ... – David19801

+0

你甚至试图在te php文档中查看该部分的数组函数吗? – dbf

回答

5

回复与array_values()设置数组索引:

$thearray = array_values($thearray); 
print_r($thearray); 
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); 
+0

'array_filter'将保留旧的索引。 – clentfort

+0

我得到:语法错误,意外T_FUNCTION – David19801

+0

你使用什么版本的PHP? – Baba

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