本文介绍了在递归PHP越来越阵列级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的下一个树阵:
$arr =
array(
'id' => 1431,
'children' => array(
1432 => array(
'id' => 1432,
'children' => array(
1433 => array(
'id' => 1433,
'children' => array(),
),
1434 => array(
'id' => 1434,
'children' => array(),
),
)
),
1435 => array(),
'id' => 1435,
'children' => array(
1436 => array(
'id' => 1436,
'children' => array(
1437 => array(
'id' => 1437,
'children' => array(),
),
1438 => array(
'id' => 1438,
'children' => array(),
),
1439 => array(
'id' => 1439,
'children' => array(),
),
),
),
),
),
);
我的任务,从这个数组代阵列。
我的输出应该是下一个:
My task to get generations array from this array.My output should be the next:
Array(
[1] = Array(
[1432] = ...
[1435] = ...
),
[2] = Array(
[1433] = ...
[1434] = ...
[1436] = ...
),
[3] = Array(
[1437] = ...
[1438] = ...
[1439] = ...
),
)
但现在我的输出下一个(不含1346元):
But now my output the next (without 1346 element):
Array(
[1] = Array(
[1432] = ...
[1435] = ...
),
[2] = Array(
[1433] = ...
[1434] = ...
),
[3] = Array(
[1437] = ...
[1438] = ...
[1439] = ...
),
)
什么是错误的,我的功能?
What is wrong in my function?
public function getGenerations($userTree, $currGeneration = 0, $result = array())
{
print_r($userTree);
$currGeneration++;
if (!empty($userTree) && !empty($userTree['children'])) {
foreach($userTree['children'] as $k => $v) {
$currUser = $v;
unset($currUser['children']);
$result[$currGeneration][$k] = $currUser;
$result += $this->getGenerations($v, $currGeneration, $result);
}
}
return $result;
}
我调用这个函数是这样的: $水库= getGenerations($ ARR);
先谢谢你。对不起,我的英语水平。
I call this function like this: $res = getGenerations($arr);
Thank you in advance. Sorry for my english.
推荐答案
您可以传递的结果数组作为,而不是返回,然后与当地的结果数组加入吧:
You could pass the result array as a reference instead of returning and then joining it with the local result array:
public function getGenerations($userTree, $currGeneration = 0, &$result = array())
{
print_r($userTree);
$currGeneration++;
if (!empty($userTree) && !empty($userTree['children'])) {
foreach($userTree['children'] as $k => $v) {
$currUser = $v;
unset($currUser['children']);
$result[$currGeneration][$k] = $currUser;
$this->getGenerations($v, $currGeneration, $result);
}
}
return $result;
}
这篇关于在递归PHP越来越阵列级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!