如何将数组键更改为从 1 而不是 0 开始

新手上路,请多包涵

我在某个数组中有值我想重新索引整个数组,这样第一个值键应该是 1 而不是零,即

默认情况下,在 PHP 中,数组键从 0 开始。即 0 => a, 1=> b ,我想重新索引整个数组以从 key = 1 开始,即 1=> a, 2=> b, ....

原文由 Khurram Ijaz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 907
2 个回答
$alphabet = array("a", "b", "c");
array_unshift($alphabet, "phoney");
unset($alphabet[0]);

编辑:我决定将此解决方案与本主题中提出的其他解决方案进行基准测试。这是我使用的非常简单的代码:

 $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

原文由 Michael McTiernan 发布,翻译遵循 CC BY-SA 2.5 许可协议

如果您已经有一个数组并且想要重新索引它以从索引 X 而不是 0、1、3…N 开始,那么:

 // Check if an array is filled by doing this check.
if (count($your_array) > 0) {
    // Let's say we want to start from index - 5.
    $your_array = [5 => $your_array[0], ...array_slice($your_array, 1)];
}

关于传播运算符“…”

https://www.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat

附言

真实世界的场景/用例,我在为客户执行任务时遇到的情况:

我有一个 <div> 包含两个 <tables> 。每个 <table> 包含一周中的几天的标记。第一个有从星期一到星期四的日子。第二个有从周五到周日的日子。因此,在我的任务中,我让变量代表一周,其中每天都有几个小时的开放和关闭。我需要将那一周的变量适当地分成两部分。

 <table>
    <?php for ($dayIndex = 0; $dayIndex < 4; $dayIndex++):  ?>
        <?php
            $_timetable = array_slice($timetable, 0, 4);

            // $renderTimetableRow is an anonymous function
            // that contains a markup to be rendered, like
            // a html-component.
            $renderTimetableRow($_timetable, $dayIndex);
        ?>
    <?php endfor; ?>
</table>

<table>
    <?php for($dayIndex = 4; $dayIndex < 7; $dayIndex++):  ?>
        <?php
            if (count($_timetable = array_slice($timetable, 4, 7)) > 0) {
                $_timetable = [4 => $_timetable[0], ...array_slice($_timetable, 1)];
            }

            // $renderTimetableRow is an anonymous function
            // that contains a markup to be rendered, like
            // a html-component.
            $renderTimetableRow($_timetable, $dayIndex);
        ?>
    <?php endfor; ?>
</table>

原文由 Gromax 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题