SHOW:
|
|
- or go back to the newest paste.
| 1 | <?php | |
| 2 | ||
| 3 | $comments = array( | |
| 4 | array( | |
| 5 | 'id' => 1, | |
| 6 | 'parent_id' => 0, | |
| 7 | 'body' => 'Some comment', | |
| 8 | 'created' => 123456798, | |
| 9 | ), | |
| 10 | array( | |
| 11 | 'id' => 2, | |
| 12 | 'parent_id' => 0, | |
| 13 | 'body' => 'Some comment', | |
| 14 | 'created' => 123456798, | |
| 15 | ), | |
| 16 | array( | |
| 17 | 'id' => 3, | |
| 18 | 'parent_id' => 0, | |
| 19 | 'body' => 'Some comment', | |
| 20 | 'created' => 123456798, | |
| 21 | ), | |
| 22 | array( | |
| 23 | 'id' => 4, | |
| 24 | 'parent_id' => 0, | |
| 25 | 'body' => 'Some comment', | |
| 26 | 'created' => 123456798, | |
| 27 | ), | |
| 28 | array( | |
| 29 | 'id' => 5, | |
| 30 | 'parent_id' => 2, | |
| 31 | 'body' => 'Some comment', | |
| 32 | 'created' => 123456798, | |
| 33 | ), | |
| 34 | array( | |
| 35 | 'id' => 6, | |
| 36 | 'parent_id' => 2, | |
| 37 | 'body' => 'Some comment', | |
| 38 | 'created' => 123456798, | |
| 39 | ), | |
| 40 | ||
| 41 | ); | |
| 42 | ||
| 43 | ||
| 44 | $thread = array(); | |
| 45 | $comment_refs = array(); | |
| 46 | foreach($comments as $comment){
| |
| 47 | $parent_id = $comment['parent_id']; | |
| 48 | $comment_id = $comment['id']; | |
| 49 | ||
| 50 | if (!isset($comment_refs[$parent_id])) {
| |
| 51 | // No parent comment so just add it to the thread | |
| 52 | $thread[] = $comment; | |
| 53 | $tmp_key = count($thread) - 1; | |
| 54 | ||
| 55 | // Add a replies element to hold any future replies | |
| 56 | $thread[$tmp_key]['replies'] = array(); | |
| 57 | ||
| 58 | // Make a reference to this comment so we can find it later | |
| 59 | $comment_refs[$comment_id] = &$thread[count($thread)-1]; | |
| 60 | ||
| 61 | } else {
| |
| 62 | // Parent comment available, so add it there | |
| 63 | $comment_refs[$parent_id]['replies'][] = $comment; | |
| 64 | ||
| 65 | // Make a reference to this comment so we can find it later | |
| 66 | $replies = &$comment_refs[$parent_id]['replies']; | |
| 67 | $comment_refs[$comment_id] = &$replies[count($replies)-1]; | |
| 68 | } | |
| 69 | } | |
| 70 | ||
| 71 | unset($comment_refs); | |
| 72 | print_r($thread); |