まず、私の英語で申し訳ありません。
任意のレベルの配列を調べたいのですが、一番下のレベルから上のレベルに行き、キーの値を再帰的に更新したいのですが、例はテキストよりも優れています:
これは私のコード例です:
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
(
)
)
)
)
)
)
)
現在の位置にあるすべての子のカウントを累積して合計し、前のレベルを通過して、現在のレベルのすべてのカウントを再び累積し、それがアップレベルになります。
皆様のご協力に感謝いたします。前もって感謝します。
編集
@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;
}