puggan icon

Group database rows and glue the html togheter

puggan | PRO | 12/27/12 12:18:43 AM UTC | 0 ⭐ | 544 👁️ | Never ⏰ | []
PHP |

1.25 KB

|

None

|

0 👍

/

0 👎

<?php
 
    /** define settings **/
    /* what "glue" to use between 2 news_items */
    $item_separator = "\n";
    /* how many news_items there should be in each group */
    $item_group_size = 3;
    /* what glue to use between 2 groups */
    $item_group_separator = "<div class='line'></div>\n";
    /* the database query to fetch the items */
    $query = "SELECT * FROM news";
 
    /* make 2 list to store html texts before we glue them togheter */
    $news_items = array();
    $news_item_groups = array();
 
 
    /** fetch and make html of each database row **/
    $resource = mysql_query($resource) OR die('query failed');
    while($result = mysql_fetch_assoc($resource))
    {
        /* design html for each row */
        $news_html = "<div class='news_item'>";
        $news_html .= "<h1>{$result['title']}</h1>";
        $news_html .= "<p>{$result['content']}</p>";
        $news_html .= "</div>";
 
        /* store html in list */
        $news_items[] = $news_html;
    }
 
    /* split items up in groups */
    foreach(array_chunk($news_items, $item_group_size) as $news_items_group)
    {
        /* glue each item in a group togheter and store in the 2nd list */
        $news_item_groups[] = implode($item_separator, $news_items_group);
    }
 
    /* glue each group togheter */
    echo implode($item_group_separator, $news_item_groups);

Comments