php实现无限级嵌套评论回复代码

代码语言:php

所属分类:其他

代码描述:使用php的数组排序和递归实现无限级嵌套评论及回复代码。

代码标签: php 嵌套 评论 回复 无限

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php

//模拟数据库取出的数组,评论时间字段省略
$data = array(
    array('id' => 1, 'pid' => 0, 'article_id' => 1, 'path' =>

        '01,', 'author' => 'falcon', 'content' => '这是评论的内容,content #1 <a
href="">雕刻时光</a>'),
    array('id' => 2, 'pid' => 0, 'article_id' => 1, 'path' =>

        '02,', 'author' => 'chen', 'content' => 'content #2'),
    array('id' => 3, 'pid' => 1, 'article_id' => 1, 'path' =>

        '01,03,', 'author' => 'xx', 'content' => 'content #3回复评论#1'),
    array('id' => 4, 'pid' => 0, 'article_id' => 1, 'path' =>

        '04,', 'author' => 'falcon4', 'content' => 'content #4'),
    array('id' => 5, 'pid' => 3, 'article_id' => 1, 'path' =>

        '01,03,05,', 'author' => 'falcon5', 'content' => 'content #5,回复评论#3'),
    array('id' => 6, 'pid' => 5, 'article_id' => 1, 'path' =>

        '01,03,05,06,', 'author' => 'falcon6', 'content' => 'content #6,回复评
论'),
    array('id' => 7, 'pid' => 1, 'article_id' => 1, 'path' =>

        '01,07,', 'author' => 'falcon7', 'content' => 'content #7,回复评论#1'),
    array('id' => 8, 'pid' => 4, 'article_id' => 1, 'path' =>

        '04,08,', 'author' => 'falcon', 'content' => 'content #8,回复评论#4'),
    array('id' => 9, 'pid' => 6, 'article_id' => 1, 'path' =>

        '01,03,05,06,09,', 'author' => 'falcon9', 'content' => 'content #9,回复评论
#6'),
    array('id' => 10, 'pid' => 1, 'article_id' => 1, 'path' =>

        '01,10,', 'author' => 'falcon10', 'content' => 'content #10,回复评论#1'),
    array('id' => 11, 'pid' => 3, 'article_id' => 1, 'path' =>

        '01,03,11,', 'author' => 'falcon11', 'content' => 'content #11,回复评论
#3'),
    array('id' => 12, 'pid' => 0, 'article_id' => 1,

        'path' => '12,', 'author' => 'falcon12', 'content' => 'content #12,原始评论
        '),
    array('id' => 13, 'pid' => 0, 'article_id' => 1, 'path' =>

        '13,', 'author' => 'falcon', 'content' => '测试超链接:<a href
="">我那打了酱油的微博</a>')
);

//先按path排序,如果数据库取得时已经按path排序则可不进行这一步
foreach ($data as $row) {
    $volume[] = $row['path'];
}
/*
  *预留这里对$volume 进行自定义排序 使用uasort,否则当前只能对id<100评
论有效,当然也可以通过在前面继续加0
  *如000将对<1000以内有效。0000则<10000诸如此类
  *待解决
  */
array_multisort($volume, SORT_ASC, $data);

#01,03,11应排在01,03,05之后,01,07之前
$newData = array();
foreach ($data as &$v) {
    $split = explode(',', $v['path']);
    $i = $split[0];
    $level = count($split)-1;
    $v['lv'] = $level;
    $newData[$i][] = $v;
}
$new.........完整代码请登录后点击上方下载按钮下载查看

网友评论0