简体   繁体   中英

In PHP, how can I iterate through an array and change the key dynamically?

I have an array $people . When I do print_r($people) , I get the following results:

[people] => Array
(
  [500] => Array
          (
              [firstName] => Fred
              [age] => 19
          )

  [501] => Array
          (
               [firstName] => Bob
               [age] => 12
          )
  [502] => Array
          (
               [firstName] => Steve
               [age] => 52
          )
)

I want to change all the keys to look more "normal", starting at 0, then 1, 2 etc. How can I achieve this? To clarify, I want the resulting array to look like this:

    [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);

Simply like this:

foreach ($people as $value) {
  $people_new[] = $value;
}

Try this

$people['people'] = array_values($people['people']);
print_r($people);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM