4

我正在设计评论系统,但我的递归函数存在一些问题。如果在下面查看此代码:

$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]
)

我该如何解决这个功能问题?

4

2 回答 2

6

我认为您正在使一个简单的任务变得复杂....一个简单的循环就足够了

$final = array();
foreach ( $list as $value ) {
    $final[] = !$value['parent'] 
               ? setParentStyleComment($value)
               : setReplyStyleComment($value);
}

print_r($final);

输出

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]
)

观看现场演示

于 2012-12-19T22:48:26.317 回答
2

递归?

$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)
);

$comments = array_map(function($item) {
    return sprintf(
      'id: %d - parent: %d - [%s]', 
       $item['id'], $item['parent'], $item['parent'] ? 'REPLY' : 'PARENT');
}, $list);

echo "<pre>";
print_r($comments);
echo "</pre>\n<br/>";

如(完整)示例所示,这是一个简单的array_map操作。

于 2012-12-19T22:48:16.627 回答