首先,对不起我的英语。
我想要浏览任何级别的数组,但我想在底层进入升级并递归更新键值,但是一个例子比文本更好:
这是我的示例代码:
Array
(
[1] => Array
(
[ItemText] => Home
[ItemLink] => index.php
[count] => 0
[id] => 1
[ParentID] =>
[Children] => Array
(
[2] => Array
(
[ItemText] => Home Sub 1
[ItemLink] => somepage.php
[id] => 2
[count] => 0
[ParentID] => 1
[Children] => Array
(
[3] => Array
(
[ItemText] => Home Sub 2
[ItemLink] => somepage2.php
[id] => 3
[count] => 1
[ParentID] => 2
[Children] => Array
(
)
)
[4] => Array
(
[ItemText] => Contact
[ItemLink] => contact.php
[id] => 4
[count] => 1
[ParentID] => 2
[Children] => Array
(
)
)
)
)
)
)
)
记下任何级别的数组中的计数键。每个级别都是“当前”位置的子级。我需要这个:
Array
(
[1] => Array
(
[ItemText] => Home
[ItemLink] => index.php
[count] => **2**
[id] => 1
[ParentID] =>
[Children] => Array
(
[2] => Array
(
[ItemText] => Home Sub 1
[ItemLink] => somepage.php
[id] => 2
[count] => **2**
[ParentID] => 1
[Children] => Array
(
[3] => Array
(
[ItemText] => Home Sub 2
[ItemLink] => somepage2.php
[id] => 3
[count] => 1
[ParentID] => 2
[Children] => Array
(
)
)
[4] => Array
(
[ItemText] => Contact
[ItemLink] => contact.php
[id] => 4
[count] => 1
[ParentID] => 2
[Children] => Array
(
)
)
)
)
)
)
)
我想累积并计算当前位置中所有孩子的数量,然后通过prev水平并再次累计当前水平的所有计数,并且达到上一级别。
感谢你的帮助。提前谢谢。
修改
我根据自己的需要调整了@HamzaKubba的功能,这对我有用。我把它放在需要的地方:
function explore(& $node) {
$count = 0;
if (count($node) > 0) {
foreach ($node as &$value) {
if (!isset($value['count']))
$value['count'] = 0;
if (count($value['Children']) > 0)
$value['count'] += explore($value['Children']);
$count += $value['count'];
}
}
return $count;
}
答案 0 :(得分:2)
通用模板的伪代码:
function explore(node) {
foreach (child of node) {
explore(child)
}
// now that we're done with children, do logic/calculation here
doSomething(node)
}
你想要的伪代码(根据我的理解):
function explore(node) {
foreach (child of node) {
node.count = node.count + explore(child)
}
return node.count
}
更正新代码:
function explore_($node) {
if (!isset($node['count']))
$node['count'] = 0;
foreach ($node['Children'] as $child) {
$node['count'] = $node['count'] + explore_($child);
}
return $node['count'];
}