questions on sort array by time in php(php中按时间排序数组的问题)
问题描述
---数组 $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中按时间排序数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:php中按时间排序数组的问题
基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01