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

时间:2016-11-09 20:58:46

标签: php array-merge

我有两个阵列:

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

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用array_merge(获取一个数组),array_unique(以消除重复项)和usort(以正确的顺序获取它们)来执行此操作:

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

eval.in上看到它。

答案 1 :(得分:0)

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