我有两个数组$days_order
和$mysql_result
,我想使用$mysql_result
数组对$days_order
数组进行排序。我想以天数升序显示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
)
)
答案 0 :(得分:1)
将usort
与自定义比较功能结合使用。
类似的东西:
usort($ranked, function($a, $b) {
if ($a['day'] === $b['day']) return 0;
return ($a['day'] > $b['day']) ? -1 : 1;
});
您可以阅读有关此功能的更多信息here。
答案 1 :(得分:1)
您可以在use
的比较函数中usort
自定义订单数组,如下所示:
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;
答案 2 :(得分: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;
}