我有两个数组$days_order
和$mysql_result
,我想用$days_order
数组对$mysql_result
数组进行排序。我想显示MySQL的结果在天的顺序升序?有没有办法做到这一点或任何其他方式,让我可以通过$days_order
在MySQL查询OrderBy
部分?
$days_order = Array([0] => 2[1] => 3[2] => 4[3] => 5 [4] => 6[5] => 7[6] => 1);
$mysql_result = Array (
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[day] => 3
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[day] => 2
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[day] => 1
)
)
我想在$days_order
中排序数组
Array
(
[0] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[day] => 2
)
[1] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[day] => 3
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[day] => 1
)
)
使用usort
自定义比较函数
类似:
usort($ranked, function($a, $b) {
if ($a['day'] === $b['day']) return 0;
return ($a['day'] > $b['day']) ? -1 : 1;
});
我使用了以下脚本:
function sort_array_custom_compare($mysql_result,$days_order)
{
uasort($mysql_result, function($a,$b) use ($days_order){
foreach($days_order as $value){
if($a['day'] == $value){
return 0;
break;
}
if($b['day'] == $value){
return 1;
break;
}
}
});
return $mysql_result;
}
您可以在usort
的比较函数中use
自定义订单数组:
usort($mysql_result, function ($a, $b) use ($days_order) {
// Then check the position of the 'day' value of each element
// against the position of that value in $days_order.
$a = array_search($a['day'], $days_order);
$b = array_search($b['day'], $days_order);
if ($a < $b) return -1;
if ($a == $b) return 0;
return 1;
});
如果你想在MySQL中这样做,你可以使用
ORDER BY (`day` + 1) % 7
或者,如果需要比仅仅改变日期更复杂,您可以使用CASE来提供特定的顺序(尽管这个CASE只是做同样的事情):
ORDER BY
CASE
WHEN `day` = 2 THEN 0
WHEN `day` = 3 THEN 1
WHEN `day` = 4 THEN 2
WHEN `day` = 5 THEN 3
WHEN `day` = 6 THEN 4
WHEN `day` = 7 THEN 5
WHEN `day` = 1 THEN 6
END;