NONAME_2 Posted December 1, 2010 Share Posted December 1, 2010 hi everybody, i have a php code; it returns year,month,item(post) and works with foreach but year,month display similar as sample:2010 December for all posts:confused:! $select = mysql_query("SELECT title, id, dateColumn FROM theTable"); $list = array(); while( $row = mysql_fetch_assoc($select) ) { $year = date("Y", $row['dateColumn']); $month = date("m", $row['dateColumn']); $list["$year"]["$month"][] = '<a href="site address by $row[id]">' .$row['title']. '</a>'; } foreach($list as $years) { echo "$year : "; foreach($years as $months) { echo "$month : "; foreach($months as $item) echo $item; } } I use $key=>$value but it doesn't work...TNX. Quote Link to comment Share on other sites More sharing options...
OldWest Posted December 1, 2010 Share Posted December 1, 2010 Can you clarify the output a bit more? What are you expecting as output? Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 1, 2010 Share Posted December 1, 2010 I really don't understand what the problem is based upon your description. But, looking at the code I think I know what the problem is. After you run the query and define the array $list, you then run a foreach loop on $list to output the records. But, inside that loop you are echoing $year and $month. Those variables were assinged values on each iterration of the while loop. So, when it comes time to run the foreach loop $month and $year will always display the last values defined in the previous while loop. You could solve this by modifying your foreach loops like this: foreach($list as $year => $years) foreach($months as $month => $item) But a better solution would be to revise your query and only process the records once $query = "SELECT title, id, dateColumn FROM theTable ORDER BY dateColumn ASC"; $result = mysql_query($query); $current_year = false; $current_month = false; while($row = mysql_fetch_assoc($result) ) { $year = date("Y", $row['dateColumn']); $month = date("m", $row['dateColumn']); if($current_year != $year) { echo "$year : "; } if($current_month != $month || $current_year != $year) { echo "$month : "; } $current_year = $year; $current_month = $month; echo "<a href=\"site address by {$row['id']}\">{$row['title']}</a>"; } Quote Link to comment Share on other sites More sharing options...
NONAME_2 Posted December 1, 2010 Author Share Posted December 1, 2010 hi mjdamato, your code is correct, TNX for your attension. Quote Link to comment 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.