如何在 PHP 中重新索引数组但索引从 1 开始? [英] How do you reindex an array in PHP but with indexes starting from 1?

查看:32
本文介绍了如何在 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 开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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