我有两个数组:
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
(获取一个数组)、array_unique
(消除重复项)和 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);
合并并删除重复项后,为每个唯一日期使用
array_multisort()
和 unix 值的临时数组,以避免 strtotime()
调用体内出现过多的 usort()
调用。
换句话说,
array_map('strtotime'...)
将为每个元素精确调用 1 次 strtotime()
,但在 strtotime()
的每次迭代中调用 usort()
两次将始终超过 (O)n。以下是更高效的方式。
代码:(演示)
$result = array_unique(array_merge($a, $b));
array_multisort(array_map('strtotime', $result), $result);
var_export($result);