如何更改数组键从 1 而不是 0 开始 [英] how to change the array key to start from 1 instead of 0
本文介绍了如何更改数组键从 1 而不是 0 开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在某个数组中有值我想重新索引整个数组,这样第一个值键应该是 1 而不是零,即
I have values in some array I want to re index the whole array such that the the first value key should be 1 instead of zero i.e.
默认情况下,在 PHP 中,数组键从 0 开始.即 0 =>a,1=>b
,我想重新索引整个数组以从 key = 1 开始,即 1=>a,2=>b, ....
By default in PHP the array key starts from 0. i.e. 0 => a, 1=> b
, I want to reindex the whole array to start from key = 1 i.e 1=> a, 2=> b, ....
推荐答案
$alphabet = array("a", "b", "c");
array_unshift($alphabet, "phoney");
unset($alphabet[0]);
我决定将此解决方案与本主题中提出的其他解决方案进行基准测试.这是我使用的非常简单的代码:
I decided to benchmark this solution vs. others posed in this topic. Here's the very simple code I used:
$start = microtime(1);
for ($a = 0; $a < 1000; ++$a) {
$alphabet = array("a", "b", "c");
array_unshift($alphabet, "phoney");
unset($alphabet[0]);
}
echo (microtime(1) - $start) . "\n";
$start = microtime(1);
for ($a = 0; $a < 1000; ++$a) {
$stack = array('a', 'b', 'c');
$i= 1;
$stack2 = array();
foreach($stack as $value){
$stack2[$i] = $value;
$i++;
}
$stack = $stack2;
}
echo (microtime(1) - $start) . "\n";
$start = microtime(1);
for ($a = 0; $a < 1000; ++$a) {
$array = array('a','b','c');
$array = array_combine(
array_map(function($a){
return $a + 1;
}, array_keys($array)),
array_values($array)
);
}
echo (microtime(1) - $start) . "\n";
和输出:
0.0018711090087891
0.0021598339080811
0.0075368881225586
这篇关于如何更改数组键从 1 而不是 0 开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文