php 如何重新索引数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11224821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:00:43  来源:igfitidea点击:

How to reindex an array?

phparrays

提问by stergosz

My array looks like this:

我的数组如下所示:

array(
  0 => 'val',
  2 => 'val',
  3 => 'val',
  5 => 'val',
  7 => 'val'
);

How can I reset the keys so it will go like 0, 1, 2, 3, 4?

我怎样才能重置钥匙,让它像这样0, 1, 2, 3, 4

回答by Emil Vikstr?m

Use array_values:

使用array_values

$reindexed_array = array_values($old_array);

回答by alekveritov

array_splice($old_array, 0, 0);

It will not sort array and will not create a second array

它不会对数组进行排序,也不会创建第二个数组

回答by Rawkode

By using sort($array);

通过使用 sort($array);

See PHP documentation here.

请参阅此处的PHP 文档。

I'd recommend sortover array_valuesas it will not create a second array. With the following code you now have two arrays occupying space: $reindexed_array and $old_array. Unnecessary.

我建议sort结束,array_values因为它不会创建第二个数组。使用以下代码,您现在有两个数组占用空间:$reindexed_array 和 $old_array。不必要。

$reindexed_array = array_values($old_array);

$reindexed_array = array_values($old_array);

回答by fvlgnn

array_splice($jam_array, 0, count($jam_array));

To sort an array with missing intermediate indices, with countthe order is more secure. So 0is the first index and count($jam_array)or sizeof($jam_array)return the decimal position of the array, namely, last index.

要对缺少中间索引的数组进行排序,使用count的顺序更安全。所以0是第一个索引和/count($jam_array)sizeof($jam_array)返回数组的小数位,即最后一个索引。

回答by mickmackusa

From PHP7.4, you can reindex without a function call by unpacking the values into an array with the splat operator. Consider this a "repack".

从 PHP7.4 开始,您可以通过使用 splat 运算符将值解包到数组中而无需函数调用即可重新索引。将此视为“重新打包”。

Code: (Demo)

代码:(演示

$array = array(
  0 => 'val',
  2 => 'val',
  3 => 'val',
  5 => 'val',
  7 => 'val'
);

$array = [...$array];

var_export($array);

Output:

输出:

array (
  0 => 'val',
  1 => 'val',
  2 => 'val',
  3 => 'val',
  4 => 'val',
)

Note: this technique will NOTwork on associative keys (the splat operator chokes on these). Non-numeric demo

注意:此技术不适用于关联键(splat 运算符会阻塞这些键)。非数字演示

The breakage is reported as an inability to unpack stringkeys, but it would be more accurate to say that the keys must all be numeric. Integer as string demoand Float demo

破损报告为无法解压缩字符串键,但更准确地说键必须都是数字。 整数作为字符串演示浮点演示