2017-10-06 166 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 
)