Php 如何根据当前时间对多维数组进行排序?

Php 如何根据当前时间对多维数组进行排序?,php,arrays,Php,Arrays,我有一个类似的数组 我想要的是,假设时间是11:30,我希望第三个arraytime->14:00位于数组的第一个位置,其余的位于它下面。我使用的是PHP5.3,这就是我所能做的 输出应为: 使用usort进行以下操作: usort($array, function ($a, $b) { $aTime = strtotime(date('Y-m-d ' . $a['time'])); $bTime = strtotime(date('Y-m-d ' . $b['time']));

我有一个类似的数组

我想要的是,假设时间是11:30,我希望第三个arraytime->14:00位于数组的第一个位置,其余的位于它下面。我使用的是PHP5.3,这就是我所能做的

输出应为:

使用usort进行以下操作:

usort($array, function ($a, $b) {
   $aTime = strtotime(date('Y-m-d ' . $a['time']));
   $bTime = strtotime(date('Y-m-d ' . $b['time']));
   $time = strtotime(date('Y-m-d 13:00'));

   if ($aTime > $time && $bTime < $time)
       return -1; // $a is in future, while $b is in past
   elseif ($aTime < $time && $bTime > $time)
       return 1; // $a is in past, while $b is in future
   else
       return $aTime - $bTime; // $a and $b is either in future or in past, sort it normally.
});

您可以使用此回调来进行usort:

解释 首先,以HH:MM格式检索当前时间。一个字符被附加到它,以确保输入数组中的任何时间字符串都不会与它完全匹配。这将确保以当前时间作为参数,以输入日期作为其他参数调用strcmp时,不会返回0,而是返回-1或1。请注意,-1表示第一个参数小于第二个参数。1的意思正好相反

传递给usort的回调将针对多对输入时间字符串调用,并应返回一个负值或正值或0,以指示该对在输出中的排序方式:负值表示第一个值应在第二个值之前,0表示它们完全相同,并且可以以任何方式排序,1表示第二个应在第一个之前订购

这里的返回值是三个值的乘积,每个值都是strcmp的结果。第二个和第三个永远不能为零

当第二个和第三个值都等于1或都等于-1时,这意味着两个输入时间位于当前时间的同一侧:要么都在当前时间之前,要么都在当前时间之后。这两个因素的乘积为1

当这些值不相等时,一个为1,另一个为-1,则表示两个输入时间位于当前时间的不同侧面,因此它们的顺序应该相反。然后乘积为-1

最后,第一个因素告诉我们两个输入值之间的比较情况。当上面提到的乘积为-1时,这应该是相反的,实际上乘法会处理这个问题。

在PHP7中

usort($arr, function($a, $b)
{
  $t = time();
  $a = $t < ($a = strtotime($a['time'])) ? $a : $a + 86400; // +1 day
  $b = $t < ($b = strtotime($b['time'])) ? $b : $b + 86400;
  return $a <=> $b;
});

@rahul不,所有排序功能都会更改array@trincot您可以通过答案中的注释来描述它是如何工作的。毫无疑问,您的解决方案是正确的。@commonsense,我添加了一个解释。@Rahul,我添加了一个解释。
usort($array, function ($a, $b) {
   $aTime = strtotime(date('Y-m-d ' . $a['time']));
   $bTime = strtotime(date('Y-m-d ' . $b['time']));
   $time = strtotime(date('Y-m-d 13:00'));

   if ($aTime > $time && $bTime < $time)
       return -1; // $a is in future, while $b is in past
   elseif ($aTime < $time && $bTime > $time)
       return 1; // $a is in past, while $b is in future
   else
       return $aTime - $bTime; // $a and $b is either in future or in past, sort it normally.
});
$t = date("h:m") . "_"; // add a character so it cannot be EQUAL to any time in the input
usort($arr, function ($a, $b) use ($t) {
    return strcmp($a["time"],$b["time"]) * strcmp($t,$a["time"]) * strcmp($t,$b["time"]);
});
usort($arr, function($a, $b)
{
  $t = time();
  $a = $t < ($a = strtotime($a['time'])) ? $a : $a + 86400; // +1 day
  $b = $t < ($b = strtotime($b['time'])) ? $b : $b + 86400;
  return $a <=> $b;
});