我正在使用PHP从SQL查询中检索日期,而且我似乎无法根据这个相当简单的数组来了解如何显示每年及其月份:
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 ) )
我想要展示的是:
2012 - July - June 2011 - May
答案 0 :(得分:3)
$myarray = array();
foreach ($array as $key => $value)
{
$myarray[$value->year][] = $value->monthname;
}
print_r($myarray);
现在你有一个这样的数组:
Array
(
[2010] => Array(
[0] => 'June',
// ...
),
[2011] => Array(
// ...
),
// ...
)
快速而肮脏的解决方案
$year = '';
foreach ($array as $key => $value)
{
if ($value->year != $year)
{
$year = $value->year;
echo $year.'<br />';
}
echo ' - '.$value->monthname.'<br />';
}