PHP按日期和年份分开数据

时间:2013-10-29 21:04:38

标签: php arrays foreach

我有这样的数据

Title - August 2013
Title2 - August 2013
Title3 - October 2013

我想要做的是写出按日期分开这些内容并返回每月和每年的链接,我的预期结果是:

August 2013
October 2013

我开始编写这段代码:

<?php 

$data = array("Title - August 2013", "Title2 - August 2013", "Title3 - October 2013");

foreach($data as $index){

    $date = explode(" - ", $index);

    echo $date[1];

}

?>

我只是不知道如何仅仅显示一次约会。我想我可以在foreach中创建一个数组,并检查日期是否在数组中。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

嗯,是的...把日期放到数组然后删除重复项:

$data = array('Title - August 2013', 'Title2 - August 2013', 'Title3 - October 2013');

$dates = array();
foreach($data as $index) {
    $date = explode(' - ', $index);
    $dates[] = $date[1];
}

$dates = array_unique($dates);

var_dump($dates);

结果将是:

array (size=2)
  0 => string 'August 2013' (length=11)
  2 => string 'October 2013' (length=12)