gpt4 book ai didi

php - array_values 递归 php

转载 作者:可可西里 更新时间:2023-11-01 13:21:30 24 4
gpt4 key购买 nike

假设我有一个这样的数组:

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
)

)

)

)

)

我想做的是将键为 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;
}

但这只重置了第一个子数组的键(键为 45 的那个)

最佳答案

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;
}

此函数从数组中实现array_values 递归:

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

排列如下:

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

关于php - array_values 递归 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11943678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com