【问题标题】:In php, how can I sort an array of lines by date when each line contains both a date and some additional text?在 php 中,当每行包含日期和一些附加文本时,如何按日期对行数组进行排序?
【发布时间】:2020-05-03 21:21:36
【问题描述】:

这是我想按日期降序排序的 php 数组内容。每行都以日期开头。每行会有多个单词:

$newarray = [
    "8-06-2001 fish",
    "10-09-2020 chips",
    "3-07-2020 peas",
    "9-09-2005 chicken",
    "5-05-1999 veg",
    "20-04-1998 sausage",
    "1-04-1998 haddock",
    "7-04-1998 cod",
    "3-04-1998 curry",
    "7-09-2005 burger",
    "1-09-2005 cheese"
];

我试过这个功能,但对文本和日期都不好:

// DATE SORT FUNCTION
$compare_function = function($a,$b) {$a_timestamp = strtotime($a); // convert string date to a int timestamp
$b_timestamp = strtotime($b); 
if ($a_timestamp > $b_timestamp) {return -1;}
elseif ($a_timestamp < $b_timestamp) {return 1;} else {return 0;}};

// USE FUNCTION
usort($newarray, $compare_function)

【问题讨论】:

  • 给定示例数据,您希望它们在排序后的顺序是什么?
  • 我想要最新的日期在顶部

标签: php arrays sorting


【解决方案1】:

问题是strtotime 如果您传递一个非日期时间字符串,将返回 false。 "8-06-2001 fish" 不是日期时间字符串,因为“鱼”不是日期或时间。因此,您的 strtotime 调用都返回 false,并且您的排序不起作用。

为了从您的字符串中提取日期字符串,您需要拆分字符串以便只得到您的日期字符串。分隔您的日期字符串和其余部分的字符(即分割"8-06-2001""fish" 的字符)是" "

因此,您需要在" " 处拆分字符串。为此,请使用explode(" ", $string),它返回一个数组。此数组中的第一个元素(即[0])是第一个" " 之前的字符串。

这是应该的代码:

    // DATE SORT FUNCTION
    $compare_function = function($a,$b) {
        $a_timestamp = strtotime(explode(" ", $a)[0]); // convert string date to a int timestamp
        $b_timestamp = strtotime(explode(" ", $b)[0]);
        if ($a_timestamp > $b_timestamp) {return -1;}
        elseif ($a_timestamp < $b_timestamp) {return 1;} else {return 0;}
    };

    // USE FUNCTION
    usort($newarray, $compare_function)

【讨论】:

  • 完美;非常感谢;这行得通。我在任何地方都找不到答案。
  • 希望我的解释也能帮助你理解它:)
【解决方案2】:

strtotime 在字符串中有非时间片段时不返回整数。试试

strtotime(current(explode(' ', $a)))

相反。这会在空格处分解字符串,获取第一部分,然后在上面执行strtotime

【讨论】:

  • 谢谢,但我不知道如何实现字符串与爆炸。我一直在努力,我会继续努力,看看能不能解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 2016-11-07
相关资源
最近更新 更多