如何改变数组键从1开始,而不是0 [英] how to change the array key to start from 1 instead of 0

查看:183
本文介绍了如何改变数组键从1开始,而不是0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某些数组值我想重新索引整个阵列,使得第一个值的关键应该是1,而不是零,即

通过在默认情况下PHP从0阵列键开始即 0 =>一,1 => b ,我想重新索引整个阵列从主要的开始= 1即 1 =>一,2 => B,....


解决方案

  $字母=阵列(A,B,C);
array_unshift($字母,假);
未设置($字母[0]);

编辑:我决定把基准这种解决方案与其他本主题中提出的。这里是非常简单的code我用:

  $开始= microtime中(1);
为($ A = 0; $ A< 1000; ++ $ A){
    $字母表=阵列(一,B,C);
    array_unshift($字母,假);
    未设置($字母[0]);
}
回声(microtime中(1) - $开始)。 \\ n;
$开始= microtime中(1);
为($ A = 0; $ A< 1000; ++ $ A){
    $堆栈=阵列('一个','B','C');
    $ I = 1;
    $ stack2中=阵列();
    的foreach($堆栈$值){
        $ stack2中[$ i] = $价值;
        $ I ++;
    }
    $堆栈= $ stack2中;
}
回声(microtime中(1) - $开始)。 \\ n;
$开始= microtime中(1);
为($ A = 0; $ A< 1000; ++ $ A){
    $阵列=阵列('A','B','C');    $阵列= array_combine(
        array_map(函数($ A){
            返回$ A + 1;
        },array_keys($阵列)),
        array_values​​($数组)
    );
}
回声(microtime中(1) - $开始)。 \\ n;

和输出:

  0.0018711090087891
0.0021598339080811
0.0075368881225586

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.

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]);

Edit: 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";

And the output:

0.0018711090087891
0.0021598339080811
0.0075368881225586

这篇关于如何改变数组键从1开始,而不是0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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