2013-07-03 55 views
2

我在嘗試對基於「調度」鍵的數組進行排序。但是,它不起作用。有沒有人有任何指示讓這個代碼工作?感謝:PHP array multisort

陣:

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()); 
} 

回答

4

我覺得它更容易只是使用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; 
} 

不是如果你正在使用PHP的舊版本,你必須定義一個單獨的函數來完成的有點像

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

不幸的是我不能讓這個函數工作。有任何想法嗎? –

+0

您使用的是哪個版本的PHP? – Orangepill

+0

發佈了一個解決方案,可以用於老版本的php。 – Orangepill

0

在附加到這隻會在PHP 5.3及以上

工作Orangepill說過,如果您使用的是5.2或更高版本,則可以使用create_function()來創建匿名(lambda樣式)函數。例如,

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