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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.