Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

php - how to change the array key to start from 1 instead of 0

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, ....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$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) . "
";


$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) . "
";


$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) . "
";

And the output:

0.0018711090087891
0.0021598339080811
0.0075368881225586

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...