php PHP按包含日期的元素对多维数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2910611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Sort a multidimensional array by element containing date
提问by Tim
I have an array such as:
我有一个数组,例如:
Array
(
[0] => Array
(
[id] => 2
[type] => comment
[text] => hey
[datetime] => 2010-05-15 11:29:45
)
[1] => Array
(
[id] => 3
[type] => status
[text] => oi
[datetime] => 2010-05-26 15:59:53
)
[2] => Array
(
[id] => 4
[type] => status
[text] => yeww
[datetime] => 2010-05-26 16:04:24
)
)
Can anyone suggest a way to sort/order this based on the datetime element?
任何人都可以建议一种基于日期时间元素对其进行排序/排序的方法吗?
回答by Ferdinand Beyer
Use usort()and a custom comparison function:
使用usort()和自定义比较函数:
function date_compare($a, $b)
{
$t1 = strtotime($a['datetime']);
$t2 = strtotime($b['datetime']);
return $t1 - $t2;
}
usort($array, 'date_compare');
EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.
编辑:您的数据组织在数组数组中。为了更好地区分这些,我们将内部数组(数据)称为记录,这样您的数据实际上就是一个记录数组。
usortwill pass two of these records to the given comparison function date_compare()at a a time. date_comparethen extracts the "datetime"field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0if both dates are equal, a positive number if the first one ($a) is larger or a negative value if the second argument ($b) is larger. usort()uses this information to sort the array.
usort将一次将这些记录中的两个传递给给定的比较函数date_compare()。 date_compare然后将"datetime"每条记录的字段提取为 UNIX 时间戳(整数),并返回差值,这样结果将是0如果两个日期相等,如果第一个 ( $a) 较大则为正数,如果第二个参数 ( $b) 更大。 usort()使用此信息对数组进行排序。
回答by Dave None
This should work. I converted the date to unix time via strtotime.
这应该有效。我通过 strtotime 将日期转换为 unix 时间。
foreach ($originalArray as $key => $part) {
$sort[$key] = strtotime($part['datetime']);
}
array_multisort($sort, SORT_DESC, $originalArray);
One-liner version would be using multiple array methods:
单行版本将使用多种数组方法:
array_multisort(array_map('strtotime',array_column($originalArray,'datetime')),
SORT_DESC,
$originalArray);
回答by Federkun
From php7 you can use the Spaceship operator:
在 php7 中,您可以使用Spaceship 运算符:
usort($array, function($a, $b) {
return new DateTime($a['datetime']) <=> new DateTime($b['datetime']);
});
回答by Toby
http://us2.php.net/manual/en/function.array-multisort.phpsee third example:
http://us2.php.net/manual/en/function.array-multisort.php见第三个例子:
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
fyi, using a unix (seconds from 1970) or mysql timestamp (YmdHis - 20100526014500) would be be easier for the parser but i think in your case it makes no difference.
仅供参考,使用unix(从1970年开始的秒数)或mysql时间戳(YmdHis - 20100526014500)对解析器来说会更容易,但我认为在你的情况下它没有区别。
回答by falko
Sorting array of records/assoc_arrays by specified mysql datetime field and by order:
按指定的 mysql 日期时间字段和顺序对记录/assoc_arrays 数组进行排序:
function build_sorter($key, $dir='ASC') {
return function ($a, $b) use ($key, $dir) {
$t1 = strtotime(is_array($a) ? $a[$key] : $a->$key);
$t2 = strtotime(is_array($b) ? $b[$key] : $b->$key);
if ($t1 == $t2) return 0;
return (strtoupper($dir) == 'ASC' ? ($t1 < $t2) : ($t1 > $t2)) ? -1 : 1;
};
}
// $sort - key or property name
// $dir - ASC/DESC sort order or empty
usort($arr, build_sorter($sort, $dir));
回答by Ajit Kumar
$array = Array
(
[0] => Array
(
[id] => 2
[type] => comment
[text] => hey
[datetime] => 2010-05-15 11:29:45
)
[1] => Array
(
[id] => 3
[type] => status
[text] => oi
[datetime] => 2010-05-26 15:59:53
)
[2] => Array
(
[id] => 4
[type] => status
[text] => yeww
[datetime] => 2010-05-26 16:04:24
)
);
print_r($array);
$name = 'datetime';
usort($array, function ($a, $b) use(&$name){
return $a[$name] - $b[$name];});
print_r($array);
回答by Faisal
You can simply solve this problem using usort()with callback function. No need to write any custom function.
您可以使用带有回调函数的usort()简单地解决这个问题。无需编写任何自定义函数。
$your_date_field_name = 'datetime';
usort($your_given_array_name, function ($a, $b) use (&$your_date_field_name) {
return strtotime($a[$your_date_field_name]) - strtotime($b[$your_date_field_name]);
});
回答by Borjovsky
For 'd/m/Y'dates:
对于'd/m/Y'日期:
usort($array, function ($a, $b, $i = 'datetime') {
$t1 = strtotime(str_replace('/', '-', $a[$i]));
$t2 = strtotime(str_replace('/', '-', $b[$i]));
return $t1 > $t2;
});
where $iis the array index
$i数组索引在哪里
回答by Immutable Brick
I came across to this post but I wanted to sort by time when returning the items inside my class and I got an error.
我遇到了这篇文章,但我想在返回班级中的项目时按时间排序,但出现错误。
So I research the php.net website and end up doing this:
所以我研究了 php.net 网站并最终这样做:
class MyClass {
public function getItems(){
usort( $this->items, array("MyClass", "sortByTime") );
return $this->items;
}
public function sortByTime($a, $b){
return $b["time"] - $a["time"];
}
}
You can find very useful examples in the PHP.net website
您可以在PHP.net 网站中找到非常有用的示例
My array looked like this:
我的阵列看起来像这样:
'recent' =>
array
92 =>
array
'id' => string '92' (length=2)
'quantity' => string '1' (length=1)
'time' => string '1396514041' (length=10)
52 =>
array
'id' => string '52' (length=2)
'quantity' => string '8' (length=1)
'time' => string '1396514838' (length=10)
22 =>
array
'id' => string '22' (length=2)
'quantity' => string '1' (length=1)
'time' => string '1396514871' (length=10)
81 =>
array
'id' => string '81' (length=2)
'quantity' => string '2' (length=1)
'time' => string '1396514988' (length=10)

