問題描述
---數組 $points----
Array
(
[0] => Array
(
[0] => 2011-10-02 05:30:00
[1] => 20
)
[1] => Array
(
[0] => 2011-10-04 09:30:00
[1] => 12
)
[2] => Array
(
[0] => 2011-10-01 13:30:00
[1] => 25
)
[3] => Array
(
[0] => 2011-10-03 02:30:00
[1] => 31
)
)
我在上面有一個數組,想按時間對這個數組進行排序.然后我使用以下代碼進行排序并且結果是正確的.但是,如果我將代碼time[$key] = $val[0]
改為$time = $val[0]
,結果是錯誤的.
I have an array at above and would like to sort this array by time. Then I used the code as following to sort and result is correct. However, if I changed the code time[$key] = $val[0]
to $time = $val[0]
, the result is wrong.
有沒有人可以向我解釋一下?非常感謝!
Is there anyone can explain this to me? Many thanks!
foreach($points as $key=>$val){
$time[$key] = $val[0];
array_multisort($time, SORT_ASC, $points);
}
推薦答案
array_multisort
一次對多個數組進行排序.但是,它適用于列數組,因此需要 foreach
循環來獲取時間列.建立此列表后,您可以執行多重排序.$points
數組根據 $times
中的索引進行排序,按照 文檔中的這個例子.
array_multisort
sorts more than one array at once. However, it works on an array of columns, so the foreach
loop is needed to get a column of the times. After building up this list, you can then perform the multisort. The $points
array is ordered according to the indices in $times
, as per this example in the docs.
但是,您不需要在 foreach
中執行排序,因為這意味著排序發生了 4 次(在您的示例中).它只需要發生一次:
However, you don't need to perform the sort inside the foreach
, as that means the sort happens 4 times (in your example). It only needs to happen once:
foreach ($points as $key => $val) {
$time[$key] = $val[0];
}
array_multisort($time, SORT_ASC, $points);
這篇關于php中按時間排序數組的問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!