我有一个多维数组,可能包含或不包含键name
一次或多次。我想做的是,对于所述元素的每个实例,使用键key
在该元素旁边插入另一个元素。
所以,给定这个数组:
[
[
'noname' => 'No name',
'label' => 'I have no name'
],
[
'name' => 'foo',
'label' => 'Foo',
'fields' => [
[
'name' => 'bar',
'label' => 'Bar'
]
]
],
[
'name' => 'baz',
'label' => 'Baz'
]
]
我想要以下输出:
[
[
'noname' => 'No name',
'label' => 'I have no name'
],
[
'name' => 'foo',
'key' => 'foo-key', # This is inserted by the function
'label' => 'Foo',
'fields' => [
[
'name' => 'bar',
'key' => 'bar-key', # This is inserted by the function
'label' => 'Bar'
]
]
],
[
'name' => 'baz',
'key' => 'baz-key', # This is inserted by the function
'label' => 'Baz'
]
]
我已查看array_walk_recursive
但无法让它发挥作用。我是否需要编写自己的递归函数,或者是否有适合我的内置函数?
答案 0 :(得分:2)
您的代码将是这样的:
<?php
$array = [
[
'noname' => 'No name',
'label' => 'I have no name'
],
[
'name' => 'foo',
'label' => 'Foo',
'fields' => [
[
'name' => 'bar',
'label' => 'Bar'
]
]
],
[
'name' => 'baz',
'label' => 'Baz'
]
];
function fix_array($array){
foreach ($array as $key => $value){
if (is_array($value)){
$array[$key] = fix_array($value);
}
elseif ($key == 'name'){
$array['key'] = $value . '-key';
}
}
return $array;
}
$new_array = fix_array($array);
print_r($new_array);