[英]In PHP, how can I iterate through an array and change the key dynamically?
我有一个数组$people
。 当我执行print_r($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
)
)
内置函数array_values()将仅从数组中获取值,而忽略键,而是返回从零开始重新编号的数组。
$people = array_values($people);
就像这样:
foreach ($people as $value) {
$people_new[] = $value;
}
尝试这个
$people['people'] = array_values($people['people']);
print_r($people);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.