我不擅长递归,但最近我被要求处理太多。
我不得不递归地生成一个多维数组并在这里找到了一种方法:Recursive function to generate multidimensional array from database result
但是我现在还需要计算每个父母有多少孩子,我不知道我将如何采用下面的功能来实现这一点?
function generateCorrectArray(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $key => $element) {
if ($element['parent'] == $parentId) {
$children = generateCorrectArray($elements, $element['category_id']);
if ($children) {
$element['children'] = $children;
}
$branch[$element['category_id']] = $element;
}
}
return $branch;
}
编辑
我开始的数组:
$someArray = array(
array(
"id"=> 1,
"name"=> "somename1",
"parent"=> 0,
"childrenCount" => 0,
"children" => 0
),
array(
"id"=> 53,
"name"=> "somename2",
"parent"=> 1,
"childrenCount" => 0,
"children" => 0
),
array(
"id"=> 921,
"name"=> "somename3",
"parent"=> 53,
"childrenCount" => 0,
"children" => 0
)
当前函数结果
$someArray = array(
array(
"id"=> 1,
"name"=> "somename1",
"parent"=> 0,
"children" => array(
array(
"id"=> 53,
"name"=> "somename2",
"parent"=> 1,
"children" => array(
array(
"id"=> 921,
"name"=> "somename3",
"parent"=> 53,
"children" => array(
)
)
)
)
)
)
我希望它对每个嵌套的孩子也有一个计数。
目标
$someArray = array(
array(
"id"=> 1,
"name"=> "somename1",
"parent"=> 0,
"childrenCount"=> 2,
"children" => array(
array(
"id"=> 53,
"name"=> "somename2",
"parent"=> 1,
"childrenCount"=> 1,
"children" => array(
array(
"id"=> 921,
"name"=> "somename3",
"parent"=> 53,
"childrenCount"=> 0,
"children" => array(
)
)
)
)
)
)
先谢谢了。