Problem:
Here are 3 layers of nested comments, parent=0 for a first-level comment, parent=3 to indicate that the parent comment has an ID of 3
$comments = Array ( ' id ' = ' 3 ', ' parent ' = ' 0 ' ), array ( ' id ' = ' 9 ', ' PA Rent ' = ' 0 ' ), array ( ' id ' = ' 1 ', ' parent ' = ' 3 ' ), array ( ' id ' = ' 2 ', ' Parent ' = ' 3 ' ), array ( ' id ' = ' 5 ', ' parent ' = ' 1 ' ) , Array ( c22/> ' id ' = ' 7 ', ' parent ' = ' 1 ' );
The stupidest way to achieve the effect I want
$sub = Array (), foreach ($comments as $a) { if ($a [' parent '] = = 0) { foreach ($comments as $b) { if ($b [' Paren T '] = = $a [' id ']) { foreach ($comments as $c) { if ($c [' parent '] = = $b [' id ']) { $b [' Children '] [] = $c; } } $a [' children '] [] = $b; } } $sub [] = $a; }} Echo ' <pre> ';p rint_r ($sub);
The print is the effect I want, the sub-comment as a sub-array of the parent comment, but as I write this can not be nested multi-layered comments, infinite pole nesting to do so?
Thank you for asking for help!
Solution:
Is it possible to understand the problem of infinite classification?
Infinite class Classification $list = Array (' ID ' =>1, ' fid ' =>0, ' title ' = ' China '), array (' ID ' =>2, ' fid ' = 1, ' title ' = ' Jiangsu '), array (' ID ' =>3, ' fid ' =>1, ' title ' = ' Anhui '), array (' ID ' =>4, ' fid ' =>8, ' Title ' = ' Jiangyin '), array (' ID ' =>5, ' fid ' =>3, ' title ' = ' Wuhu '), array (' ID ' =>6, ' fid ' =>3, ' titl E ' = ' + ' Hefei '), array (' ID ' =>7, ' fid ' =>3, ' title ' = ' Bengbu '),); $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;
Related articles:
PHP Comment Reply Solution
Use the PHP wireless level to implement the comment reply function in categories
Using JS to achieve the perfect imitation QQ space comment reply effect