use*_*368 7 php arrays recursion multidimensional-array
假设我有一个这样的数组:
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
)
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
我要做的是用键children,0,1,2,3等重置数组的键,而不是45,56或57.
我尝试过类似的东西:
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;
}
Run Code Online (Sandbox Code Playgroud)
但是只重置第一个子数组的键(带键45的键)
您使用递归方法,但不在任何地方分配函数调用的返回值$this->array_values_recursive($value);。$arr当您在循环中进行修改时,第一级有效。由于上述原因,任何进一步的级别都不再起作用。
如果你想保留你的功能,请按如下方式更改(未经测试):
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;
}
Run Code Online (Sandbox Code Playgroud)