Heim > Artikel > Backend-Entwicklung > 关于php评论回复无限极嵌套如何实现?已写基本代码,期待高手解惑
问题:
下面是有3层嵌套的评论,parent=0表示一级评论,parent=3表示父评论的id为3
$comments = array ( array ( 'id' => '3', 'parent' => '0' ), array ( 'id' => '9', 'parent' => '0' ), array ( 'id' => '1', 'parent' => '3' ), array ( 'id' => '2', 'parent' => '3' ), array ( 'id' => '5', 'parent' => '1' ) , array ( 'id' => '7', 'parent' => '1' ) );
最笨的办法,实现我要的效果
$sub = array (); foreach ($comments as $a) { if ($a['parent'] == 0) { foreach ($comments as $b) { if ($b['parent'] == $a['id']) { foreach ($comments as $c) { if ($c['parent'] == $b['id']) { $b['children'][] = $c; } } $a['children'][] = $b; } } $sub[] = $a; } } echo '<pre class="brush:php;toolbar:false">'; print_r($sub);
打印出来的就是我要的效果,子评论作为父评论的子数组,但像我这么写没法嵌套多层评论,无限极嵌套要这么实现呢?
请求帮助,感激不尽!
解决方案:
是不是可以理解为 无限级 分类的问题?
// 无限级分类 $list = array( array('id'=>1, 'fid'=>0, 'title' => '中国'), array('id'=>2, 'fid'=>1, 'title' => '江苏'), array('id'=>3, 'fid'=>1, 'title' => '安徽'), array('id'=>4, 'fid'=>8, 'title' => '江阴'), array('id'=>5, 'fid'=>3, 'title' => '芜湖'), array('id'=>6, 'fid'=>3, 'title' => '合肥'), array('id'=>7, 'fid'=>3, 'title' => '蚌埠'), ); $new = array(); foreach($list as $v){ $new[$v['fid']][] = $v; } $i = 0; $j = 0; $a = true; $p[$i] = 0; $q[$j] = $i; while($a){ $next = false; $i = $q[$j]; $var = $new[$i]; if(!isset($p[$i])){ $p[$i] = 0; } if($p[$i] == count($var)){ echo '</ul>'; }else{ for($k=$p[$i]; $k<count($var);$k++){ if($k == 0) echo '<ul>'; echo '<li>'.$var[$k]['title']; $p[$i]++; if(isset($new[$var[$k]['id']])){ $i = $var[$k]['id']; $j++; $q[$j] = $i; $next = true; break; } echo '</li>'; if($k == count($var)-1){ echo '</ul>'; } } } if($next){ continue; } $j--; if($j < 0){ break; } } exit;
相关文章: