Array_values ​​recursive php

Say I have an array like this:

Array ( [id] => 45 [name] => john [children] => Array ( [45] => Array ( [id] => 45 [name] => steph [children] => Array ( [56] => Array ( [id] => 56 [name] => maria [children] => Array ( [60] => Array ( [id] => 60 [name] => thomas ) [61] => Array ( [id] => 61 [name] => michelle ) ) ) [57] => Array ( [id] => 57 [name] => luis ) ) ) ) ) 

What I'm trying to do is reset the array keys with children keys to 0, 1, 2, 3, etc. instead of 45, 56 or 57.

I tried something like:

 function array_values_recursive($arr) { foreach ($arr as $key => $value) { if(is_array($value)) { $arr[$key] = array_values($value); $this->array_values_recursive($value); } } return $arr; } 

But what reset only the key of the first child array (the one with key 45)

+4
source share
5 answers

You use a recursive approach, but you do not assign a return value to the function call $this->array_values_recursive($value); anywhere. The first level works when you change $arr in a loop. Any additional level no longer works for the specified reasons.

If you want to save your function, change it as follows (unchecked):

 function array_values_recursive($arr) { foreach ($arr as $key => $value) { if (is_array($value)) { $arr[$key] = $this->array_values_recursive($value); } } if (isset($arr['children'])) { $arr['children'] = array_values($arr['children']); } return $arr; } 
+3
source
 function array_values_recursive($arr) { $arr2=[]; foreach ($arr as $key => $value) { if(is_array($value)) { $arr2[] = array_values_recursive($value); }else{ $arr2[] = $value; } } return $arr2; } 

this function, which implements array_values_recursive from an array like:

 array( 'key1'=> 'value1', 'key2'=> array ( 'key2-1'=>'value-2-1', 'key2-2'=>'value-2-2' ) ); 

for an array like:

 array( 0 => 'value1', 1 => array ( 0 =>'value-2-1', 1 =>'value-2-2' ) ); 
+1
source

This should do it:

 function array_values_recursive($arr, $key) { $arr2 = ($key == 'children') ? array_values($arr) : $arr; foreach ($arr2 as $key => &$value) { if(is_array($value)) { $value = array_values_recursive($value, $key); } } return $arr2; } 
0
source

Try it,

  function updateData($updateAry,$result = array()){ foreach($updateAry as $key => $values){ if(is_array($values) && count($values) > 0){ $result[$key] = $this->_updateData($values,$values); }else{ $result[$key] = 'here you can update values'; } } return $result; } 
0
source

You can use php fnc walk_array_recursive here

0
source

All Articles