我已经实现了第一个目标,第二个目标并不完全。
这是迄今为止的功能。
$count = 0;
function findObj($arr) {
global $count;
foreach($arr as $key => $value) {
if(gettype($arr[$key]) == 'array') {
// append the string "here" to the array found
$arr[$key][] = 'here';
$count++;
// call same function within function with the argument of array found
findObj($arr[$key]);
}
}
$rtnArr = [$count, $arr];
return $rtnArr;
}
var_dump(findArr($arr));
// this returns
array (size=5)
0 => int 1
1 => int 44
2 => int 43
3 =>
array (size=2)
0 => string 'hello' (length=5)
1 => string 'here' (length=4)
4 =>
array (size=4)
0 => string 'one' (length=3)
1 => string 'two' (length=3)
2 =>
array (size=2)
0 => string 'three' (length=5)
1 => string 'four' (length=4)
3 => string 'here' (length=4)
仅修改第一级中的数组。请帮助我的大脑即将爆炸()。
答案 0 :(得分:1)
<?php
$input =
[
[
'foo',
[
'bar',
'baz',
[
'bat',
'man'
]
]
]
];
function add_extra_element_recursive(array &$array)
{
foreach($array as $key => &$value) {
if(is_array($value)) {
add_extra_element_recursive($value);
}
}
$array[] = 'extra';
}
var_export($input);
echo "\n";
add_extra_element_recursive($input);
var_export($input);
输出:
array (
0 =>
array (
0 => 'foo',
1 =>
array (
0 => 'bar',
1 => 'baz',
2 =>
array (
0 => 'bat',
1 => 'man',
),
),
),
)
array (
0 =>
array (
0 => 'foo',
1 =>
array (
0 => 'bar',
1 => 'baz',
2 =>
array (
0 => 'bat',
1 => 'man',
2 => 'extra',
),
3 => 'extra',
),
2 => 'extra',
),
1 => 'extra',
)