4

I have an array which looks like-

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
    )
)  

I used substr() function to get particular part-

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

Now It is showing output like -

January 2017  
January 2017  
February 2017  
February 2017   

But I want Output like -

 January 2017  
February 2017 

I tried as follows but didn't get proper output-

$unique_dates = array_map(
                    'unserialize',
                     array_unique(
                         array_map(
                             'serialize',
                             $dates
                         )
                     )
                );

I want to remove duplicates values.
How is this possible?
Thanks.

7
  • 1
    give it a try php.net/manual/en/function.array-unique.php Commented Jan 5, 2017 at 6:46
  • So this will be your array to make unique right ? $monthName." ".$year Commented Jan 5, 2017 at 6:46
  • @VforVendetta yeah right Commented Jan 5, 2017 at 6:49
  • $arr = [ "January 2017","January 2017","February 2017","February 2017" ]; print_r(array_unique($arr)); This is simple answer then, but I think you want something different Commented Jan 5, 2017 at 6:51
  • as @VforVendetta said, array_unique is working as you asked deepak... Array ( [0] => January 2017 [2] => February 2017 ) this is the o/p I got Commented Jan 5, 2017 at 6:57

1 Answer 1

1

run it like this:

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>';});
Sign up to request clarification or add additional context in comments.

1 Comment

@ Kris sorry for late reply. This is exactly what I wanted. Thanks for help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.