コメント システムを設計していますが、再帰関数に問題があります。以下のこのコードを見てください:
$list = array(
array('id'=>1,'parent'=>0),
array('id'=>2,'parent'=>1),
array('id'=>3,'parent'=>0),
array('id'=>4,'parent'=>0),
array('id'=>5,'parent'=>4),
array('id'=>6,'parent'=>4)
);
$c = count($list);
$comment = array();
function setParentStyleComment($cmnt){
return 'id: '.$cmnt['id'].' - parent: '.$cmnt['parent'].' - [PARENT]';
}
function setReplyStyleComment($cmnt){
return 'id: '.$cmnt['id'].' - parent: '.$cmnt['parent'].' - [REPLY]';
}
function getComment($p) {
global $comment,$list,$c;
foreach($list as $L){
if(($L['parent'] == 0 || $L['parent'] != $p) && $L['id'] != $p)
{
$comment[] = setParentStyleComment($L);
$x = $L['id'];
array_shift($list);
getComment($x);
}
else if($L['id'] != $p)
{
$comment[] = setReplyStyleComment($L);
$x = $L['id'];
array_shift($list);
if($x < $c){
getComment($x);
}
}
}
}
getComment(0);
echo "<pre>";
print_r($comment);
echo "</pre>\n<br/>";
上記のコードの結果は次のとおりです。
Array
(
[0] => id: 1 - parent: 0 - [PARENT]
[1] => id: 2 - parent: 1 - [REPLY]
[2] => id: 3 - parent: 0 - [PARENT]
[3] => id: 4 - parent: 0 - [PARENT]
[4] => id: 5 - parent: 4 - [REPLY]
[5] => id: 6 - parent: 4 - [PARENT]
)
ただし、次の結果が必要です。
Array
(
[0] => id: 1 - parent: 0 - [PARENT]
[1] => id: 2 - parent: 1 - [REPLY]
[2] => id: 3 - parent: 0 - [PARENT]
[3] => id: 4 - parent: 0 - [PARENT]
[4] => id: 5 - parent: 4 - [REPLY]
[5] => id: 6 - parent: 4 - [REPLY]
)
この関数の問題を解決するにはどうすればよいですか?