php - Loop through array and display year once, months after

619

I'm retrieving dates from an SQL query with PHP, and I can't seem to get my head around how to display each year and its months based on this rather simple array:

Array
(
    [0] => stdClass Object
        (
            [monthname(wp_posts.post_date)] => July
            [year(wp_posts.post_date)] => 2012
        )

    [1] => stdClass Object
        (
            [monthname(wp_posts.post_date)] => June
            [year(wp_posts.post_date)] => 2012
        )

    [2] => stdClass Object
        (
            [monthname(wp_posts.post_date)] => May
            [year(wp_posts.post_date)] => 2011
        )

)

What I want to be displayed is this:

2012
- July
- June
2011
- May
413

Answer

Solution:

$myarray = array();

foreach ($array as $key => $value)
{
    $myarray[$value->year][] = $value->monthname;
}

print_r($myarray);

Now you have a array like this:

Array
(
  [2010] => Array(
      [0] => 'June',
      // ...
  ),
  [2011] => Array(
     // ...
  ),
  // ...
)

QUICK AND DIRTY SOLUTION

$year = '';

foreach ($array as $key => $value)
{
  if ($value->year != $year)
  {
    $year = $value->year;
    echo $year.'<br />'; 
  }
  echo ' - '.$value->monthname.'<br />';
}

People are also looking for solutions to the problem: php - display data of form in html

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.