aen*_*rew 3 php arrays sorting multidimensional-array
我有以下数组:
[0] => Array
(
[name] => The Name
[description] => description
[date] => Thur, May 5 @ 7:00 p.m.
[rating] => PG
[year] => 2011
)
[1] => Array
(
[name] => Name 2
[description] => description 2
[date] => Sun, May 8 @ 7:30 p.m.
[rating] => 14A
[year] => 2011
)
Run Code Online (Sandbox Code Playgroud)
还有大约5-10个零件.
我最终想要做的是使用数组的日期部分按天分组这些项目(即"所有带有"日期"的项目"落入"5月8日"应按此分组).
知道怎么回事吗?请注意,"日期"字段存储在DB中 - 这不是从date()转换的时间戳; 管他呢.
非常感谢!
创建自己的排序函数并使用usort调用它.
例如(不考虑时间戳格式的复杂性):
function date_sort($a, $b) {
return strcmp($a['date'], $b['date']); //only doing string comparison
}
usort($array, 'date_sort');
Run Code Online (Sandbox Code Playgroud)
要完成date_sort,您将需要将日期转换为可比较的类型.这是一个将它们转换为UNIX时间戳的解决方案:
function convert_date($time) {
$time = substr($time, strpos($time, ',')+1);
$time = str_replace('@', ',', $time);
$time = str_replace('.', '', $time);
return strtotime($time);
}
function date_sort($a, $b) {
$a = convert_date($a['date']);
$b = convert_date($b['date']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
Run Code Online (Sandbox Code Playgroud)