特定数组与 php 中的日期合并

Specific array merge with dates in php

我有两个数组:

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

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

我需要将它们合并为一个并按日期排序以获得如下内容:

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"
]

我该怎么做?

您可以使用 array_merge (to get one array), array_unique (to eliminate duplicates) and usort 执行此操作(以正确的顺序排列它们):

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

eval.in 上查看 运行。

<?php

function _sort($a, $b)
{
    $a = DateTime::createFromFormat('d M Y', $a);
    $b = DateTime::createFromFormat('d M Y', $b);

    if ($a == $b) return 0;

    return ($a < $b) ? -1 : 1;
}

$a =  [
  0 => "1 Oct 2016",
  1 => "2 Oct 2016",
  2 => "3 Oct 2016",
  3 => "4 Oct 2016",
  4 => "5 Oct 2016",
];

$b = [
  0 => "29 Sep 2016",
  1 => "30 Sep 2016",
  2 => "1 Oct 2016",
  3 => "2 Oct 2016",
  4 => "3 Oct 2016",
];

$merged = array_merge($a, $b);
# sort
usort($merged, '_sort');

print_r($merged);