📅  最后修改于: 2023-12-03 14:52:48.384000             🧑  作者: Mango
在PHP中,可以使用数组函数重新索引数组。本篇文章将介绍两种主要的方法:使用array_values()
和使用array_combine()
。
使用array_values()
函数可以返回新数组,其中的键值将从0开始顺序排列。
$fruits = array("Apple", "Banana", "Cherry");
// 重新索引数组
$fruits = array_values($fruits);
// 输出结果
print_r($fruits);
输出结果:
Array
(
[0] => Apple
[1] => Banana
[2] => Cherry
)
如果想要自定义新数组的键值,可以使用array_combine()
函数,将自定义的键名与原数组的值对应起来,从而创建新的键值对数组。
$fruits = array("Apple", "Banana", "Cherry");
$index = array("A", "B", "C");
// 重新索引数组
$fruits = array_combine($index, $fruits);
// 输出结果
print_r($fruits);
输出结果:
Array
(
[A] => Apple
[B] => Banana
[C] => Cherry
)
以上就是在PHP中重新索引数组的两种方法。使用array_values()
可以很方便地将键值从0开始排列,而使用array_combine()
可以根据自己的需求自定义数组的键值。