I am programming a section of a website which contains a stream of posts. The posts are of various size, but contain only text. What I wish to do is take the text of the posts from the server, then:
-
Organize them into Large, Medium, and Small size posts by the number of characters they contain.

-
Combine the posts into a stack such that when it is displayed, all of the posts are flush with the edges. This requires that every row of posts is of the same width.

The posts are in a div that is set to automatically put the posts on the next line when they overflow, so the only issue is placing the posts in the div in the right order.
For example, the code for figure/image 2 is:
<div class="small_posts" ></div><div class="medium_posts"></div>
<div class="medium_posts"></div><div class="small_posts" ></div>
<div class="small_posts" ></div><div class="tiny_posts" ></div><div class="tiny_posts"></div>
The text for the posts comes in a linear array from a MySQL database, and I am receiving and displaying it with PHP.
My issue is not how to implement this in PHP, but rather how to design an algorithm to do this in the first place.
My attempted designed so far have been shoddy hacks, of too little quality to mention.
I would greatly appreciate some advice on how to design an algorithm to efficiently sort these posts into flush rows.
You can find also the solution with javascript
Check it out this plugin http://masonry.desandro.com/