這篇文章主要介紹php實作暢言留言板和網易跟帖樣式,有興趣的朋友參考下,希望對大家有幫助。
暢言留言板樣式:
網跟貼文樣式:
##原理
#需要在評論表中添加兩個主要字段id 和pid ,其他字段隨意添加,例如文章id、回覆時間、回覆內容、回覆人甚麼的。 其中pid就是目前已經回覆過的評論的id。 從上圖可以看出,裡面每一層的pid就是他上一層評論的id。仔細觀察下上面的版面。是不是很像PHP中的多維數組?如果你能想到,那就簡單了。 實作方法
1.前台:這個比較簡單 就是p嵌p。然後設定p的border和margin padding就行了
<p class="comment"> <p class="comment"> <p class="comment"> </p> </p> </p> <p class="comment"> </p>
然後直接讀出這個表中的所有評論。可以得到如下數組
Array ( [0] => Array ( [id] => 1 [pid] => [content] => 评论1 ) [1] => Array ( [id] => 2 [pid] => [content] => 评论2 ) [2] => Array ( [id] => 3 [pid] => [content] => 评论3 ) [3] => Array ( [id] => 4 [pid] => 1 [content] => 评论4回复评论1 ) [4] => Array ( [id] => 5 [pid] => 1 [content] => 评论5回复评论1 ) [5] => Array ( [id] => 6 [pid] => 2 [content] => 评论6回复评论2 ) [6] => Array ( [id] => 7 [pid] => 4 [content] => 评论7回复评论4 ) [7] => Array ( [id] => 8 [pid] => 7 [content] => 评论8回复评论7 ) [8] => Array ( [id] => 9 [pid] => 8 [content] => 评论9回复评论8 ) [9] => Array ( [id] => 10 [pid] => 8 [content] => 评论10回复评论8 ) )
其中$array就是上面讀取出來的數組,首先取出pid預設為空的,然後遞歸,在取出pid為當前評論id的數組
public static function tree($array,$child="child", $pid = null) { $temp = []; foreach ($array as $v) { if ($v['pid'] == $pid) { $v[$child] = self::tree($array,$child,$v['id']); $temp[] = $v; } } return $temp; }
重組後,可以得到下面的這個數組,可以看到,這個數組的樣式已經和前台評論樣式很像了
Array ( [0] => Array ( [id] => 1 [pid] => [content] => 评论1 [child] => Array ( [0] => Array ( [id] => 4 [pid] => 1 [content] => 评论4回复评论1 [child] => Array ( [0] => Array ( [id] => 7 [pid] => 4 [content] => 评论7回复评论4 [child] => Array ( [0] => Array ( [id] => 8 [pid] => 7 [content] => 评论8回复评论7 [child] => Array ( [0] => Array ( [id] => 9 [pid] => 8 [content] => 评论9回复评论8 [child] => Array ( ) ) [1] => Array ( [id] => 10 [pid] => 8 [content] => 评论10回复评论8 [child] => Array ( ) ) ) ) ) ) ) ) [1] => Array ( [id] => 5 [pid] => 1 [content] => 评论5回复评论1 [child] => Array ( ) ) ) ) [1] => Array ( [id] => 2 [pid] => [content] => 评论2 [child] => Array ( [0] => Array ( [id] => 6 [pid] => 2 [content] => 评论6回复评论2 [child] => Array ( ) ) ) ) [2] => Array ( [id] => 3 [pid] => [content] => 评论3 [child] => Array ( ) ) )
得到上面的數組後,再用遞迴輸出即可
public static function traverseArray($array) { foreach ($array as $v) { echo "<p class='comment' style='width: 100%;margin: 10px;background: #EDEFF0;padding: 20px 10px;border: 1px solid #777;'>"; echo $v['content']; if ($v['child']) { self::traverseArray($v['child']); } echo "</p>"; } }
以上是php實作暢言留言板和網易跟帖樣式的詳細內容。更多資訊請關注PHP中文網其他相關文章!