从数组中删除重复的值

4

我有一个数组,它看起来像这样-

Array
(
    [0] => stdClass Object
    (
        [post_date] => 2017-01-04 14:28:00
    )

    [1] => stdClass Object
    (
        [post_date] => 2017-01-05 11:06:00
    )

    [2] => stdClass Object
    (
        [post_date] => 2017-02-04 14:28:00
    )

    [3] => stdClass Object
    (
        [post_date] => 2017-02-04 14:34:00
    )
)  

我使用了substr()函数来获取特定部分-
foreach($unique_dates as $val) { 
    $year=substr($val->post_date,0,4);
    $month=substr($val->post_date,5,2);
    $monthName = date('F', mktime(0, 0, 0, $month, 10)); 
    echo $monthName." ".$year."<br>";
}  

现在它的输出如下 -
January 2017  
January 2017  
February 2017  
February 2017   

但我希望得到这样的输出格式 -
 January 2017  
February 2017 

我尝试了以下方法,但没有得到合适的输出结果-
$unique_dates = array_map(
                    'unserialize',
                     array_unique(
                         array_map(
                             'serialize',
                             $dates
                         )
                     )
                );

我想要移除重复的数值。
这个怎么实现?
谢谢。


1
尝试一下:http://php.net/manual/zh/function.array-unique.php - Ahad
所以这将是您创建唯一数组的代码吗?$monthName." ".$year - Rahul
@VforVendetta 是的没错。 - amM
如果您想重新索引输出,那么可以使用以下代码:array_values(array_unique($arr))。但是,这是否符合您的要求呢? - Rahul
问题不完全相同,但您可以按照@xFighter的建议在此帖子中获得答案。https://dev59.com/R4Lba4cB1Zd3GeqPZxpL - DevStarlight
显示剩余2条评论
1个回答

1

像这样运行它:

foreach($unique_dates as $val) { 
    $year=substr($val->post_date,0,4);
    $month=substr($val->post_date,5,2);
    $monthName = date('F', mktime(0, 0, 0, $month, 10)); 
    $result[] = $monthName." ".$year;
} 
$result = array_flip($result); // here will remove the duplicate value, and return as the keys of the array.
array_walk($results, function($v, $k){echo $k.'<br>';});

1
@ Kris 抱歉回复晚了。这正是我想要的。感谢你的帮助。 - amM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接