Search code examples
phparray-merge

Specific array merge with dates in php


I've got two arrays:

array:5 [▼
  0 => "1 Oct 2016"
  1 => "2 Oct 2016"
  2 => "3 Oct 2016"
  3 => "4 Oct 2016"
  4 => "5 Oct 2016"
]

and

array:5 [▼
  0 => "29 Sep 2016"
  1 => "30 Sep 2016"
  2 => "1 Oct 2016"
  3 => "2 Oct 2016"
  4 => "3 Oct 2016"
]

I need to merge them into one with sort by date to get something like this:

array:7 [▼
  0 => "29 Sep 2016"
  1 => "30 Sep 2016"
  2 => "1 Oct 2016"
  3 => "2 Oct 2016"
  4 => "3 Oct 2016"
  5 => "4 Oct 2016"
  6 => "5 Oct 2016"
]

How can i do this?


Solution

  • You can do this with array_merge (to get one array), array_unique (to eliminate duplicates) and usort (to get them in the right order):

    $c = array_unique(array_merge($a, $b));
    usort($c, function($a, $b) { return strtotime($a) - strtotime($b); });
    

    See it run on eval.in.