Advertisement
puggan

Group database rows and glue the html togheter

Dec 26th, 2012
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.25 KB | None | 0 0
  1. <?php
  2.  
  3.     /** define settings **/
  4.     /* what "glue" to use between 2 news_items */
  5.     $item_separator = "\n";
  6.     /* how many news_items there should be in each group */
  7.     $item_group_size = 3;
  8.     /* what glue to use between 2 groups */
  9.     $item_group_separator = "<div class='line'></div>\n";
  10.     /* the database query to fetch the items */
  11.     $query = "SELECT * FROM news";
  12.  
  13.     /* make 2 list to store html texts before we glue them togheter */
  14.     $news_items = array();
  15.     $news_item_groups = array();
  16.  
  17.  
  18.     /** fetch and make html of each database row **/
  19.     $resource = mysql_query($resource) OR die('query failed');
  20.     while($result = mysql_fetch_assoc($resource))
  21.     {
  22.         /* design html for each row */
  23.         $news_html = "<div class='news_item'>";
  24.         $news_html .= "<h1>{$result['title']}</h1>";
  25.         $news_html .= "<p>{$result['content']}</p>";
  26.         $news_html .= "</div>";
  27.  
  28.         /* store html in list */
  29.         $news_items[] = $news_html;
  30.     }
  31.  
  32.     /* split items up in groups */
  33.     foreach(array_chunk($news_items, $item_group_size) as $news_items_group)
  34.     {
  35.         /* glue each item in a group togheter and store in the 2nd list */
  36.         $news_item_groups[] = implode($item_separator, $news_items_group);
  37.     }
  38.  
  39.     /* glue each group togheter */
  40.     echo implode($item_group_separator, $news_item_groups);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement