Replace Array Keys with Ascending Numbers

I have an array that looks like this:

[867324] [id] => 867324 [name] => Example1 [345786] [id] => 345786 [name] => Example2 [268531] [id] => 268531 [name] => Example3 

So, as you can see, the first elements are not in a specific order. For example, you can simply consider their random numbers. The final result that I would like to get is as follows:

 [0] [id] => 867324 [name] => Example1 [1] [id] => 345786 [name] => Example2 [2] [id] => 268531 [name] => Example3 

I tried to explode, but obviously I have to do something wrong. Any help is appreciated!

+6
source share
3 answers

This will lead to a change in the numbering of the keys while maintaining the order of the elements.

 $new_array = array_values($old_array); 
+26
source

You can reset to use array keys with array_values ​​() :

 $array = array_values($array); 

Using this method, an array such as:

 Array('123'=>'123', '456'=>'456', '789'=>'789') 

Will be renumbered as:

 Array('0'=>'123', '1'=>'456', '2'=>'789') 
+7
source

If the order of the elements doesn't matter, I believe the PHP sort method will not support indexes. http://www.php.net/manual/en/function.sort.php

 sort($array); 

Note. This function assigns new keys to elements in the array. It will remove all existing keys that can be assigned, and not just reorder the keys.

Update: This works, although the mentioned array_values ​​method makes much more sense.

+2
source

Source: https://habr.com/ru/post/914976/


All Articles