Jump to content

foreach =>Archive Date


NONAME_2

Recommended Posts

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.

 

 

Link to comment
https://forums.phpfreaks.com/topic/220326-foreach-archive-date/
Share on other sites

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>";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.