在PHP中,如何迭代数组并动态更改密钥?
我有一个数组在PHP中,如何迭代数组并动态更改密钥?,php,arrays,Php,Arrays,我有一个数组$people。当我打印($people)时,我得到以下结果: [people] => Array ( [500] => Array ( [firstName] => Fred [age] => 19 ) [501] => Array ( [firstName] => Bob
$people
。当我打印($people)时,我得到以下结果:
[people] => Array
(
[500] => Array
(
[firstName] => Fred
[age] => 19
)
[501] => Array
(
[firstName] => Bob
[age] => 12
)
[502] => Array
(
[firstName] => Steve
[age] => 52
)
)
我想改变所有的键,使其看起来更“正常”,从0开始,然后是1、2等等。我如何才能做到这一点?为了澄清,我希望生成的数组如下所示:
[people] => Array
(
[0] => Array
(
[firstName] => Fred
[age] => 19
)
[1] => Array
(
[firstName] => Bob
[age] => 12
)
[2] => Array
(
[firstName] => Steve
[age] => 52
)
)
foreach ($people as $value) {
$people_new[] = $value;
}
就这样:
[people] => Array
(
[0] => Array
(
[firstName] => Fred
[age] => 19
)
[1] => Array
(
[firstName] => Bob
[age] => 12
)
[2] => Array
(
[firstName] => Steve
[age] => 52
)
)
foreach ($people as $value) {
$people_new[] = $value;
}
内置函数将只从数组中获取值,忽略键,而是返回从零重新编号的数组
$people = array_values($people);
试试这个
$people['people'] = array_values($people['people']);
print_r($people);
不要迭代,只需使用
array\u values()
即可为您重置键:$people['people']=array\u values($people['people'])代码>