Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a comment system on 2 levels (like Blizzard http://eu.battle.net/sc2/en/blog/7935264/#c-7257875753), it's working fine but my code is a bit dirty :

// $datacoms array from mysql_query 
foreach($datacoms as $com){
    if(!$com->parent_id){
        $level_id = $com->id;
        // include the view (display the comment)

        foreach($datacoms as $com){
            if($com->parent_id == $level_id){
                // include the view (display the comment)
            }
        }
    }
}

Any better way to do it ?

share|improve this question
add comment

1 Answer

Depends on how your data is modeled. I dont know that, but I can assume that you use three relational tables. Something along these lines:

Post [parent]
+-------------+---------+
|    Field    |  Type   |
+-------------+---------+
| id          | int     |
| value       | varchar |
+-------------+---------+

Comment [parent-child]
+-------------+---------+
|    Field    |  Type   |
+-------------+---------+
| id          | int     |
| foreign_key | int     |
| value       | varchar |
+-------------+---------+

Comment->Comment [child]
+-------------+---------+
|    Field    |  Type   |
+-------------+---------+
| id          | int     |
| foreign_key | int     |
| value       | varchar |
+-------------+---------+

You are looking to potentially run three queries. An easy fix would be to add a has_children field to each parent table. With that you would save a potential checkup and easily release some complexity in the PHP loop.

    [parent-child]
    +--------------+---------+
    |    Field     |  Type   |
    +--------------+---------+
    | id           | int     |
    | foreign_key  | int     |
    | has_children | bool    | <===
    | value        | varchar |
    +--------------+---------+

I can provide the PHP code if you like, but I'm assuming that you get the general idea.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.