本文介绍了如何在PHP中重新索引数组,但索引从1开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组,我想对其重新索引,以使键反转(理想情况是从1开始):

I have the following array, which I would like to reindex so the keys are reversed (ideally starting at 1):

当前数组(该数组实际上看起来像这样):

Current array (edit: the array actually looks like this):

Array (

[2] => Object
    (
        [title] => Section
        [linked] => 1
    )

[1] => Object
    (
        [title] => Sub-Section
        [linked] => 1
    )

[0] => Object
    (
        [title] => Sub-Sub-Section
        [linked] =>
    )

)

应该如何:

Array (

[1] => Object
    (
        [title] => Section
        [linked] => 1
    )

[2] => Object
    (
        [title] => Sub-Section
        [linked] => 1
    )

[3] => Object
    (
        [title] => Sub-Sub-Section
        [linked] =>
    )

)

推荐答案

如果要重新索引从零开始,只需执行以下操作:

If you want to re-index starting to zero, simply do the following:

$iZero = array_values($arr);

如果您需要从头开始,请使用以下命令:

If you need it to start at one, then use the following:

$iOne = array_combine(range(1, count($arr)), array_values($arr));

以下是所用功能的手册页:

Here are the manual pages for the functions used:

这篇关于如何在PHP中重新索引数组,但索引从1开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:02