我正在尝试对多维数组中的数组(每个数组包含2个日期值)进行排序。我能够找到一个有用的函数来解决一个元素的问题,但我无法将其修改为两个元素。
PHP按包含日期的元素对多维数组进行排序
function date_compare($a, $b)
{
$t1 = strtotime($a['datetime']);
$t2 = strtotime($b['datetime']);
return $t1 - $t2;
}
usort($array, 'date_compare');
手头的问题是对有发布时间和编辑时间的评论进行排序。本质上,我想从最新到最旧对它们进行排序(同时保留这两个值)。
如果这不可能,请告诉我。
编辑:实物模型
$array = array(
[0] => array(
[0] => "Aug:1:2012 12:00:pm", // post date
[1] => "Aug:28:2012 12:00:pm" // edit date
),
[1] => array(
[0] => "Aug:1:2012 12:00:pm",
[1] => "Aug:30:2012 12:00:pm"
)
[2] => array(
[0] => "Aug:29:2012 12:00:pm",
[1] => "Aug:1:2012 12:00:pm"
)
};
应该首先输出:$array[1](因为它具有键1&2中的最高日期),然后输出$array[2],然后输出$sarray[0]。
$array = array(
[0] => array(
[0] => "Aug:1:2012 12:00:pm",
[1] => "Aug:30:2012 12:00:pm" // highest
),
[1] => array(
[0] => "Aug:29:2012 12:00:pm", // next
[1] => "Aug:1:2012 12:00:pm"
)
[2] => array(
[0] => "Aug:1:2012 12:00:pm",
[1] => "Aug:28:2012 12:00:pm" // lowest
)
};
您的排序函数需要首先计算出哪个日期是最近的——发布或编辑日期,然后将其用于比较。
function sort_arr($arr1, $arr2) {
$this_posted = strtotime($arr1[0]);
$this_edited = strtotime($arr1[1]);
$comparison_posted = strtotime($arr2[0]);
$comparison_edited = strtotime($arr2[1]);
$this_date = $this_posted > $this_edited ? $this_posted : $this_edited;
$comparison_date = $comparison_posted > $comparison_edited ? $comparison_posted : $comparison_edited;
return $this_date > $comparison_date;
}
$arr = array(
array("Aug:1:2009 12:00:pm", "Aug:2:2009 12:00:pm"),
array("Aug:1:2011 12:00:pm", "Jul:21:2012 12:00:pm"),
array("Aug:5:2011 12:00:pm", "Jan:21:2013 12:00:pm")
);
usort($arr, 'sort_arr');
我不确定是否理解正确,但你的意思是你想根据第1列("post-date")对数组进行排序,这些值是否相等,顺序由第2列决定。所以,你需要的只是修复你的比较功能:
function date_compare($a, $b)
{
$t1 = strtotime($a['datetime']);
$t2 = strtotime($b['datetime']);
if ($t1 != $t2) {
return $t1 - $t2;
}
// if "post dates" are equal, compare "edit dates"
$t1 = strtotime($a['datetime2']);
$t2 = strtotime($b['datetime2']);
return $t1 - $t2;
}
编辑:
好的,根据你的评论,你只需要从你的数组中提取max元素。因此,这应该有效:
usort($array, function($a, $b) {
$t1 = max(strtotime($a[0]), strtotime($a[1]));
$t2 = max(strtotime($b[0]), strtotime($b[1]));
return $t1 - $t2;
});