2017-10-06 169 views
-2

看看下面的數組:如何在數組中取消設置值後重置鍵?

$fruits = [ 
    'apple', 'banana', 'grapefruit', 'orange', 'melon' 
]; 

葡萄柚只是噁心,所以我想取消它。

$key = array_search('grapefruit', $fruit); 
unset($fruit[$key]); 

葡萄柚不在我的$fruit陣列中,但我的鑰匙不再編號正確。

array(4) { 
    [0] => 'apple' 
    [1] => 'banana' 
    [3] => 'orange' 
    [4] => 'melon' 
} 

我可以遍歷數組並創建一個新的,但我想知道是否有一個更簡單的方法來重置鍵。

+0

有.... [array_values()](http://php.net /manual/en/function.array-values.php) –

+1

3.5K代表,我發現你的重複目標只是谷歌搜索「PHP重置數組鍵「 – Epodax

+1

@Epodax您也可以在相關欄中查看:-) – jeroen

回答

4

使用array_values()

array_values($array); 

試驗結果:

[[email protected] tmp]$ cat test.php 
<?php 

$fruits = [ 
    'apple', 'banana', 'grapefruit', 'orange', 'melon' 
]; 

$key = array_search('grapefruit', $fruits); 
unset($fruits[$key]); 

// before 
print_r($fruits); 

//after 
print_r(array_values($fruits)); 
?> 

執行:

[[email protected] tmp]$ php test.php 
Array 
(
    [0] => apple 
    [1] => banana 
    [3] => orange 
    [4] => melon 
) 
Array 
(
    [0] => apple 
    [1] => banana 
    [2] => orange 
    [3] => melon 
)