PHP:重新分配数组键

duk*_*vin 4 php arrays key natsort

我有一个从降序排列的数字.当我添加到这个数组时,我添加到最后然后再做natsort($times).$ times然后看起来像这样(由print_r获得):

Array
(
    [0] => 0.01
    [1] => 0.02
    [2] => 0.05
    [3] => 0.08
    [7] => 0.10   <-- Just added and natsorted
    [4] => 0.11
    [5] => 0.14
    [6] => 0.21
)
Run Code Online (Sandbox Code Playgroud)

但是,我希望重新分配所有键,以便刚刚添加的0.10是数组索引4,这样可以很容易地看到新时间的位置.即"你的排名是$ arrayindex + 1"

除了将整个数组复制到新数组中以获取新密钥外,还有更好的方法吗?

Fel*_*ing 15

您可以使用sort [文件]SORT_NUMERIC代替,natsort:

sort($times, SORT_NUMERIC);
Run Code Online (Sandbox Code Playgroud)

不像natsort,它重新索引数组.


排序后没有内置的方法来重新索引数组.您可以在排序后使用array_values [docs]natsort:

$times = array_values($times);
Run Code Online (Sandbox Code Playgroud)

复制数组.


Gig*_*egs 7

您可以使用array_values执行此操作.

$times=array_values($times);
Run Code Online (Sandbox Code Playgroud)