开发者

Are this many embedded while-loops bad?

开发者 https://www.devze.com 2023-03-18 08:28 出处:网络
I have a while loop that gets posts from users and displays them (below).I\'d like开发者_开发技巧 to be able to display comments underneath the posts.The problem is that the posts are generated throug

I have a while loop that gets posts from users and displays them (below). I'd like开发者_开发技巧 to be able to display comments underneath the posts. The problem is that the posts are generated through a while loop. In order to generate the comments underneath each post im going to need to embed while loops. I don't know if this is possible or the right approach. Any help is appreciated.

code:

<?php
$get=mysql_query("SELECT * FROM table WHERE id='$id' ORDER BY rank DESC");
    while ($row=mysql_fetch_assoc($get)){
             $post=$row['post'];
            echo "<div class='postcontainer'>$post</div>";
            echo //i need the comments to go here
            }
  ?>


There is no rule specifying how deep the nesting can go, except that deep nesting almost invariably indicates a design flaw in the software. The description of what you are trying to do is not one such design flaw though. Best of luck.


There is no reason why you shouldn't nest while loops, and it is the preferred method for many operations. I have seen viable code go five or six loops deep. The only difference is that for large amounts of data, it will be slower, since you are increasing efficiency from O(n) to O(n^2).

I always go by the method of make it work first, optimize it second.


Yes, it is very possible to nest loops of any type in PHP. In fact, the algorithm used for the common "bubble sort" involves using a nested loop.

http://en.wikipedia.org/wiki/Bubble_sort

So no worries there. It can be tricky though...

A quick search shows an example of a bubble sort hand coded in PHP

http://www.metalshell.com/source_code/118/Bubble_Sort.html

Additionally, I have been programming for years and I have used some deeply nested loops in PHP...commonly used for navigational tree's and most recently a script that figured out what items will fit into a box to be shipped.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号