Reset array keys in a multidimensional array

I was looking for a solution for this without real success. I have a multidimensional array of parents and children with no depth restrictions. This is created from the database, but the problem is that the identifier of the element becomes the key using my way of placing a flat array in a multidimensional array, for example:

Array( [28] => Array ( [id] => 28 [color] => #ff24e5 [name] => Personal [parent_id] => [children] => Array ( [23] => Array ( [id] => 23 [color] => #41c3a3 [name] => Shopping [parent_id] => 28 [children] => Array ( [22] => Array ( [id] => 22 [color] => #8be32b [name] => Deals [parent_id] => 23 [children] => Array ( ) ) ) ) [150] => Array ( [id] => 150 [color] => #e9a3f0 [name] => Orders [parent_id] => 28 [children] => Array ( ) ) ) ) ) 

What I would like is a function that performs the following actions:

 Array ( [0] => Array ( [id] => 28 [color] => #ff24e5 [name] => Personal [parent_id] => [children] => Array ( [0] => Array ( [id] => 23 [color] => #41c3a3 [name] => Shopping [parent_id] => 28 [children] => Array ( [0] => Array ( [id] => 22 [color] => #8be32b [name] => Deals [user_id] => 1 [selected] => 0 [parent_id] => 23 [children] => Array ( ) ) ) ) [1] => Array ( [id] => 150 [color] => #e9a3f0 [name] => Orders [parent_id] => 28 [children] => Array ( ) ) ) ) ) 

Essentially, reassign the keys starting from 0. I tried many methods, but I guess I need to find a recursive solution, and when I tried this, it destroyed my array. I read the array_walk_recursive () function, but I don't quite understand what to do next. Essentially, is there a way to reset numeric keys in a multidimensional array?

Thanks for the help!

+7
source share
3 answers
 function fix_keys($array) { foreach ($array as $k => $val) { if (is_array($val)) $array[$k] = fix_keys($val); //recurse } return array_values($array); } 
+12
source

I tried to solve the same problem, here is the code

 $array = array_values($array); 
+11
source

You really need to add the is_numeric clause to stop mixing text keys ...

 function fix_keys($array) { foreach ($array as $k => $val) { if (is_array($val)) $array[$k] = $fix_keys($val); //recurse } if( is_numeric($k) ) return array_values($array); return $array; } 

I did this instead:

 function fix_keys($array) { $numberCheck = false; foreach ($array as $k => $val) { if (is_array($val)) $array[$k] = fix_keys($val); //recurse if (is_numeric($k)) $numberCheck = true; } if ($numberCheck === true) { return array_values($array); } else { return $array; } } 
+10
source

All Articles