如何在PHP中不复制数组,重新索引为从1开始的连续键
解决PHP数组重新索引为从1开始连续索引的问题
你可以通过array_combine()搭配range()和array_values()来实现需求,具体操作如下:
- 用
array_values()提取原数组的所有值,得到一个从0开始索引的纯值数组 - 用
range(1, count($x))生成从1到原数组长度的连续整数序列,作为新的索引 - 用
array_combine()将上述两个数组合并,把连续整数设为键,原数组的值设为对应值
示例代码:
$x = [1 => "uno", 2 => "dos", 5 => "tres", 6 => "cuatro"]; $x = array_combine(range(1, count($x)), array_values($x)); print_r($x);
输出结果:
Array ( [1] => uno [2] => dos [3] => tres [4] => cuatro )
如果偏好更直观的基础逻辑写法,也可以用循环实现:
$x = [1 => "uno", 2 => "dos", 5 => "tres", 6 => "cuatro"]; $newArr = []; $index = 1; foreach ($x as $value) { $newArr[$index++] = $value; } $x = $newArr;
两种方法都能实现你需要的从1开始的连续索引效果。
内容的提问来源于stack exchange,提问作者Luis Urán
相关产品推荐
相关产品推荐

