2012-11-02 39 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);