PHP数组多端口



我正试图根据关键字"dispatched"对数组进行排序。然而,它不起作用。有人有任何指针可以让这个代码工作吗?谢谢:

阵列:

Array
(
    [0] => Array
        (
            [wcccanumber] => 130700203
            [call] => SEIZURES
            [address] => 221 S PINE ST
            [county] => C
            [station] => CNB
            [department] => CANBY FIRE DISTRICT #62
            [units] => E61, M62
            [dispatched] => 20:43:59
        )
    [1] => Array
        (
            [wcccanumber] => 130700198
            [call] => CARD/RESP ARREST
            [address] => 40781 HWY 26
            [county] => C
            [station] => SAN
            [department] => SANDY FIRE DISTRICT #72
            [units] => 3709, CH37, M1, M272, R71
            [dispatched] => 19:33:27
        )
    [2] => Array
        (
            [wcccanumber] => 130700337
            [call] => TRAUMA C1
            [address] => 16500 SW CENTURY DR
            [county] => W
            [station] => SHW
            [department] => TUALATIN VALLEY FIRE & RESCUE
            [units] => E33, METWA, MW68
            [dispatched] => 21:40:13
        )
    [3] => Array
        (
            [wcccanumber] => 130700335
            [call] => FALL C1
            [address] => 48437 NW PONGRATZ RD
            [county] => W
            [station] => BUX
            [department] => BANKS FIRE DISTRICT #13
            [units] => E14, METWA, MW57, R13
            [dispatched] => 21:07:48
        )
)

代码:

public function sortActiveCalls () 
{
    foreach ($this->getActiveCalls() as $key => $val) {
           $time[$key] = $val['dispatched'];
    }
    array_multisort($time, SORT_ASC, $this->getActiveCalls());
}

我发现使用usort 更容易

 usort($array, function ($a, $b) {
       return strtotime($a["dispatched"]) - strtotime($b["dispatched"]);
 });

对于您的情况,您可以将sortActiveCalls方法重新实现为

public function sortActiveCalls(){
     $data = $this->getActiveCalls();
     usort($data, function ($a, $b) {
       return strtotime($a["dispatched"]) - strtotime($b["dispatched"]);
     });
     return $data;
}

这不会只在php5.3和以上中工作

如果您使用的是php的旧版本,则必须定义一个单独的函数来执行类似的操作

if (!function_exists("sortByDispatched")){
  function sortByDispatched($a, $b){
    return strtotime($a["dispatched"]) - strtotime($b["dispatched"]);
  }
}
usort($array, "sortByDispatched");

除了Orangepill所说的,如果您使用的是5.2或更旧版本,您可以使用create_function()创建一个匿名(lambda样式)函数。例如,

usort($array, create_function( '$a,$b', 
'return strtotime($a["dispatched"]) - strtotime($b["dispatched"]);'));

最新更新