You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中不复制数组,重新索引为从1开始的连续键

解决PHP数组重新索引为从1开始连续索引的问题

你可以通过array_combine()搭配range()和array_values()来实现需求,具体操作如下:

  1. 用array_values()提取原数组的所有值,得到一个从0开始索引的纯值数组
  2. 用range(1, count($x))生成从1到原数组长度的连续整数序列,作为新的索引
  3. 用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:31:34