PHP修复数组中的数字键

时间:2021-12-22 10:44:57

For some reason when removing items from an array I am left with keys like 0, 2, 3, 4, 6, 9 instead of 0, 1, 2, 3, 4, 5. So I am trying to figure out why, and what I can do to fix it without sorting everything via sort() as that will put stuff in order. I just want to re-key in a matter of speaking.

出于某种原因,当从数组中删除项目时,我留下了0,2,3,4,6,9等键,而不是0,1,2,3,4,5。所以我想弄清楚为什么,以及我可以做什么修复它而不通过sort()排序所有东西,因为这将把东西整理。我只是想重新说明问题。

3 个解决方案

#1


28  

Use array_values() to get the values of the original array and return them to a new array. That new array with contain new numerical keys.

使用array_values()获取原始数组的值并将它们返回到新数组。包含新数字键的新数组。

$new_array = array_values($old_array);

#2


5  

You should use array_splice() to remove elements from your array so it changes the key the way you wish at the same time.

您应该使用array_splice()从数组中删除元素,以便它以您希望的方式同时更改键。

You have to be careful with array_values() since it will not (or at least might not) work, because it may re-order your numeric indexes. If you added the value at index 0 after the value at index 3, the value at index 0 will be placed at the end of the array returned by array_values(), while it appears first in yours.

您必须小心array_values(),因为它不会(或至少可能不会)工作,因为它可能会重新排序您的数字索引。如果在索引3处的值之后添加索引0处的值,则索引0处的值将放置在array_values()返回的数组的末尾,而它首先出现在您的数组中。

#3


3  

Since the keys don't necessarily matter, you can just run your final result array through array_values(). It leaves all the values in the order they already were, resetting all the keys to sequential numeric values.

由于键不一定重要,您可以通过array_values()运行最终结果数组。它按照已有的顺序保留所有值,将所有键重置为顺序数值。

#1


28  

Use array_values() to get the values of the original array and return them to a new array. That new array with contain new numerical keys.

使用array_values()获取原始数组的值并将它们返回到新数组。包含新数字键的新数组。

$new_array = array_values($old_array);

#2


5  

You should use array_splice() to remove elements from your array so it changes the key the way you wish at the same time.

您应该使用array_splice()从数组中删除元素,以便它以您希望的方式同时更改键。

You have to be careful with array_values() since it will not (or at least might not) work, because it may re-order your numeric indexes. If you added the value at index 0 after the value at index 3, the value at index 0 will be placed at the end of the array returned by array_values(), while it appears first in yours.

您必须小心array_values(),因为它不会(或至少可能不会)工作,因为它可能会重新排序您的数字索引。如果在索引3处的值之后添加索引0处的值,则索引0处的值将放置在array_values()返回的数组的末尾,而它首先出现在您的数组中。

#3


3  

Since the keys don't necessarily matter, you can just run your final result array through array_values(). It leaves all the values in the order they already were, resetting all the keys to sequential numeric values.

由于键不一定重要,您可以通过array_values()运行最终结果数组。它按照已有的顺序保留所有值,将所有键重置为顺序数值。