在数组中取消设置值后如何重置键? [英] How to reset keys after unsetting values in an array?

查看:59
本文介绍了在数组中取消设置值后如何重置键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下数组:

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

葡萄柚只是令人作呕,所以我想取消它。

Grapefruits are just disgusting, so I would like to unset it.

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

葡萄柚是我的 $ fruit

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

我可以遍历数组并创建一个新数组,但是我想知道是否有一种更简单的方法来重置密钥。

I Could loop through the array and create a new one but I was wondering if there's a simpler method to reset the keys.

推荐答案

使用 array_values()

array_values( $array );

测试结果:

[akshay@localhost 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));
?>

执行:

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

这篇关于在数组中取消设置值后如何重置键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆