Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $comments = array(
- array(
- 'id' => 1,
- 'parent_id' => 0,
- 'body' => 'Some comment',
- 'created' => 123456798,
- ),
- array(
- 'id' => 2,
- 'parent_id' => 0,
- 'body' => 'Some comment',
- 'created' => 123456798,
- ),
- array(
- 'id' => 3,
- 'parent_id' => 0,
- 'body' => 'Some comment',
- 'created' => 123456798,
- ),
- array(
- 'id' => 4,
- 'parent_id' => 0,
- 'body' => 'Some comment',
- 'created' => 123456798,
- ),
- array(
- 'id' => 5,
- 'parent_id' => 2,
- 'body' => 'Some comment',
- 'created' => 123456798,
- ),
- array(
- 'id' => 6,
- 'parent_id' => 2,
- 'body' => 'Some comment',
- 'created' => 123456798,
- ),
- );
- $thread = array();
- $comment_refs = array();
- foreach($comments as $comment){
- $parent_id = $comment['parent_id'];
- $comment_id = $comment['id'];
- if (!isset($comment_refs[$parent_id])) {
- // No parent comment so just add it to the thread
- $thread[] = $comment;
- $tmp_key = count($thread) - 1;
- // Add a replies element to hold any future replies
- $thread[$tmp_key]['replies'] = array();
- // Make a reference to this comment so we can find it later
- $comment_refs[$comment_id] = &$thread[count($thread)-1];
- } else {
- // Parent comment available, so add it there
- $comment_refs[$parent_id]['replies'][] = $comment;
- // Make a reference to this comment so we can find it later
- $replies = &$comment_refs[$parent_id]['replies'];
- $comment_refs[$comment_id] = &$replies[count($replies)-1];
- }
- }
- unset($comment_refs);
- print_r($thread);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement