1. class Threaded_comments
  2. {
  3.  
  4. public $children = array();
  5. public $top;
  6.  
  7. /**
  8.   * @param array $comments
  9.   */
  10. function __construct($comments)
  11. {
  12. foreach ($comments as $comment)
  13. {
  14. $this->children[$comment['parent_id']][] = $comment;
  15. }
  16. }
  17.  
  18. /**
  19.   * @param array $comment
  20.   * @param int $depth
  21.   */
  22. private function format_comment($comment, $depth)
  23. {
  24. for ($depth; $depth > 0; $depth--)
  25. {
  26. echo "\t";
  27. }
  28.  
  29. echo $comment['text'];
  30. echo "\n";
  31. }
  32.  
  33. /**
  34.   * @param array $comment
  35.   * @param int $depth
  36.   */
  37. private function print_parent($comment, $depth = 0)
  38. {
  39. foreach ($comment as $c)
  40. {
  41. $this->format_comment($c, $depth);
  42.  
  43. if (isset($this->children[$c['id']]))
  44. {
  45. $this->print_parent($this->children[$c['id']], $depth + 1);
  46. }
  47. }
  48. }
  49.  
  50. public function print_comments()
  51. {
  52. foreach ($this->children[0] as $c)
  53. {
  54. if (isset($this->children[$c['id']]))
  55. {
  56. $this->print_parent($this->children[$c['id']]);
  57. }
  58. }
  59. }
  60.  
  61. }
  62.  
  63.  
  64. $comments = array(array('id'=>1, 'parent_id'=>0, 'text'=>'top'),
  65. array('id'=>2, 'parent_id'=>1, 'text'=>'Parent'),
  66. array('id'=>3, 'parent_id'=>2, 'text'=>'Child'),
  67. array('id'=>7, 'parent_id'=>2, 'text'=>'Child'),
  68. array('id'=>4, 'parent_id'=>3, 'text'=>'Child Third level'),
  69. array('id'=>5, 'parent_id'=>1, 'text'=>'Second Parent'),
  70. array('id'=>6, 'parent_id'=>5, 'text'=>'Second Child')
  71. );
  72.  
  73.  
  74. for ($foo=0;$foo<20000;$foo++)
  75. {
  76. $start = microtime(true);
  77.  
  78. $threaded_comments = new Threaded_comments($comments);
  79.  
  80. $threaded_comments->print_comments();
  81.  
  82.  
  83. $end = microtime(true);
  84. $sum += ($end-$start);
  85. }
  86. $average = $sum / 20000;