通过从中的html提取时间对php数组进行排序


sort php array by extracting time from html within

我有一个数组,其中有一些html作为值。在那个html中是日期。我想按这些日期对数组进行排序。

阵列看起来像:

Array(
    [0] => '<div class="date">April 6, 2016</div>'
    [1] => '<div class="date">January 23, 2016</div>'
    [2] => '<div class="date">March 6, 2016</div>'
    [3] => '<div class="date">December 5, 2016</div>'
)

我想要的是:

Array(
    [0] => '<div class="date">January 23, 2016</div>'
    [1] => '<div class="date">March 6, 2016</div>'
    [2] => '<div class="date">April 6, 2016</div>'
    [3] => '<div class="date">December 5, 2016</div>'
)

仅仅使用sort($array, SORT_NUMERIC)rsort()是行不通的。我的猜测是,我需要使用usort(),然后创建一个函数来比较剥离的数组值(仅日期)。但我不知道该怎么开始。

欢迎任何帮助。

编辑

我开始研究一个函数:

function strip_sort_array($a){
    foreach ($a as $key => $value) {
        $date = substr($value, 18, 32);
    }
}

这将返回日期。这可以通过strtotime转换为unix。我只需要用这个来比较一下。。。

好的,这个答案的大部分已经存在于http://php.net/manual/en/function.usort.php

所以我在这里给出代码并不觉得太糟糕。

http://sandbox.onlinephpfunctions.com/code/7b76d5119fe1aeb269d38db5ce266306e36e7c58

OP,熟悉php.net,您将能够自己解决这些问题。

function cmp($a, $b)
{
  $a=strtotime(strip_tags($a));
  $b=strtotime(strip_tags($b));
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
$date[]='<div class="date">April 6, 2016</div>';
$date[]='<div class="date">January 23, 2016</div>';
$date[]='<div class="date">March 6, 2016</div>';
$date[]='<div class="date">December 5, 2016</div>';
usort($date, "cmp");
var_export($date);

您必须将时间转换为时间戳。

http://php.net/manual/de/function.strtotime.php

然后创建一个新数组,使用时间戳作为关键字,使用html作为值。然后按键排序。