mds1256 Posted November 23, 2010 Share Posted November 23, 2010 Hello I am after some guidance on the following scenario: I have a news page that pulls from a database and would like to seperate it out by year, see below 2010 Bulletin 2 - 23/11/2010 - Some news here..... Bulletin 1 - 21/11/2010 - Some news here..... 2009 Bulletin 2 - 23/11/2009 - Some news here..... Bulletin 1 - 21/11/2009 - Some news here..... How can i do this automatically and seperate them out by year like above Quote Link to comment https://forums.phpfreaks.com/topic/219555-php-for-each-groups/ Share on other sites More sharing options...
JonnoTheDev Posted November 23, 2010 Share Posted November 23, 2010 Show your database structure please. Quote Link to comment https://forums.phpfreaks.com/topic/219555-php-for-each-groups/#findComment-1138313 Share on other sites More sharing options...
mds1256 Posted November 23, 2010 Author Share Posted November 23, 2010 Table: news id | title | date | body | picturelocation int varchar(255) date longtext varchar(100) Quote Link to comment https://forums.phpfreaks.com/topic/219555-php-for-each-groups/#findComment-1138315 Share on other sites More sharing options...
JonnoTheDev Posted November 23, 2010 Share Posted November 23, 2010 <?php $news = array(); $result = mysql_query("SELECT id, title, date, YEAR(date) AS year, SUBSTRING(body,0,100) AS snippet FROM news ORDER BY date DESC"); while($row = mysql_fetch_assoc($result)) { $news[$row['year']][] = $row; } /* display news */ foreach($news as $year => $articles) { print "<h1>".$year."</h1>"; foreach($articles as $article) { print "<p>".$article['title']." - ".date("d/m/Y", strtotime($article['date']))." - ".$article['snippet']."</p>"; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/219555-php-for-each-groups/#findComment-1138322 Share on other sites More sharing options...
mds1256 Posted November 23, 2010 Author Share Posted November 23, 2010 WOW, that was very quick and works perfect! Many thanks for this help! Quote Link to comment https://forums.phpfreaks.com/topic/219555-php-for-each-groups/#findComment-1138326 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.