この投稿と非常によく似た状況があります
PHP: 再帰関数を使用したネストされたメニュー、一部のノードのみを展開 (すべてのツリーではない)
助けが必要だ...
これが私の $menuJSONArray 変数の (部分的な) 内容です (関数を呼び出すときに使用されます):
Array
(
[0] => Array
(
[Menu_IDX] => 1
[Order] => 1
[Name] => History
[Parent] =>
[Path] => History
[Link] =>
)
[1] => Array
(
[Menu_IDX] => 2
[Order] => 25
[Name] => Review
[Parent] =>
[Path] => Review
[Link] => Review
)
[2] => Array
(
[Menu_IDX] => 3
[Order] => 35
[Name] => Past Medical History
[Parent] =>
[Path] => Past Medical History
[Link] => Past Medical History
)
[3] => Array
(
[Menu_IDX] => 4
[Order] => 45
[Name] => Item 1
[Parent] => 0
[Path] => Item 1
[Link] => Item 1
)
[4] => Array
(
[Menu_IDX] => 5
[Order] => 55
[Name] => Item 2
[Parent] => 0
[Path] => Item 2
[Link] => Item 2
)
[5] => Array
(
[Menu_IDX] => 6
[Order] => 65
[Name] => Item 3
[Parent] => 0
[Path] => Item 3
[Link] => Item 3
)
)
等々...
以下の関数を使用していますが、最初の項目でループに陥り続けています。この機能の周りに私の頭脳を包む助けが本当に必要です。前もってありがとう、このコミュニティは揺るぎません!!
///RECURSIVE MENU
function recursive($parent, $array) {
$has_children = false; //set value of has children to false by default
foreach($array as $key => $value) { //loop through the array as key-value pairs
if ($value['Parent'] == $parent) { //if the value of Parent field is equal to parent variable
if ($has_children === false && $parent) { //if children is false but parent is not null, this is a sub item
$has_children = true; //children is true
echo '<ul>' ."\n"; //create parent menu ul
} //otherwise just create the item
echo '<li>' . "\n"; //create li for parent menu item
echo '<a href="'.$value['Path'].'">' . $value['Name'] . '</a>' . " \n"; //create link for menu item
recursive($key, $array); //create sub menu
echo "</li>\n"; //end parent menu item
}
}
if ($has_children === true && $parent) echo "</ul>\n"; //end parent menu
}
?>
<?php echo recursive(0, $menuJSONArray); ?></ul>
私が見返りに得るものは次のとおりです。
<ul>
<li>
<a href="History">History</a>
<li>
<a href="History">History</a>
<li>
<a href="History">History</a>
<li>
<a href="History">History</a>
<li>
<a href="History">History</a>
<li>
<a href="History">History</a>
このループから抜け出せないようです。ありがとう!!
PS私はjqueryとcssでそれを処理するので、参照された投稿からのツリーの崩壊などには関係ありません。メニュー構文の適切な出力を取得できません。