我有以下数组。
Array
(
[1] => a
[2] => b
[3] => c
[4] => d
[5] => e
[6] => f
[7] => g
[8] => h
[9] => i
[11] => j
[13] => k
[14] => l
[15] => m
[16] => n
[17] => o
[18] => p
[19] => q
[20] => r
[21] => s
[22] => t
[23] => u
[24] => v
[25] => w
)
你可以看到10号和12号不存在。 有没有函数,所以我的数组的范围是1到23?这样看起来像这样吗?
Array
(
[1] => a
[2] => b
[3] => c
[4] => d
[5] => e
[6] => f
[7] => g
[8] => h
[9] => i
[10] => j
[11] => k
[12] => l
[13] => m
[14] => n
[15] => o
[16] => p
[17] => q
[18] => r
[19] => s
[20] => t
[21] => u
[22] => v
[23] => w
)
我希望你理解我的问题。谢谢你的帮助。
答案 0 :(得分:11)
如果您想要零索引数组:
$new = array_values($array);
如果你想以任意数字开头(在这种情况下:1);
$new = array_combine(range(1,count($array)),array_values($array));
答案 1 :(得分:3)
range()
怎么办?
$array = range('a', 'w');
更新:哦,你不是从1
到23
。你走了:
$array = array_combine(range(1,23), range('a', 'w'));
答案 2 :(得分:2)
此代码段将执行:
$new = Array();
$i = 1;
foreach ($original as $element) {
$new[$i] = $element;
$i++;
}
答案 3 :(得分:0)
您可以使用数组值来获取完整的键列表,假设索引可以从0-> 22运行,而不是1-> 23。
如果索引需要从1开始,那么添加一个额外的步骤来向前移动索引:
$newArray = array_values($array);
$startAtIndex1Array = array();
//shift indexes to start at 1
foreach($newArray as $key=>$value) {
$startAtIndex1Array[$key+1] = $value;
}
答案 4 :(得分:-1)
$tmpArray = Array
(
[1] => a
[2] => b
[3] => c
[4] => d
[5] => e
[6] => f
[7] => g
[8] => h
[9] => i
[11] => j
[13] => k
[14] => l
[15] => m
[16] => n
[17] => o
[18] => p
[19] => q
[20] => r
[21] => s
[22] => t
[23] => u
[24] => v
[25] => w
);
foreach($tmpArray as $v){
$tmpArray2[count($tmpArray2)] = $v;
}
它会执行您想要的操作,但您应该考虑通过键= 0
启动数组