我有一个对象数组的数据,如下所示。
Array(
[0]=>Object(
[event_day]=>Tuesday
)
[1]=>Object(
[event_day]=>Friday
)
[2]=>Object(
[event_day]=>Wednesday
)
)
我需要根据从星期一开始的工作日来排序,如下所示:
Array(
[0]=>Object(
[event_day]=>Tuesday
)
[1]=>Object(
[event_day]=>Wednesday
)
[2]=>Object(
[event_day]=>Friday
)
)
答案 0 :(得分:2)
对数据进行排序的代码:
$dataToSort = [
(object)['event_day' => 'Tuesday'],
(object)['event_day' => 'Friday'],
(object)['event_day' => 'Wednesday'],
];
$dayOrder = [
'Monday' => 1,
'Tuesday' => 2,
'Wednesday' => 3,
'Thursday' => 4,
'Friday' => 5,
'Saturday' => 6,
'Sunday' => 7,
];
usort($dataToSort,
function ($a, $b) use ($dayOrder) {
return $dayOrder[$a->event_day] > $dayOrder[$b->event_day];
});
print_r($dataToSort);
输出:
Array
(
[0] => stdClass Object
(
[event_day] => Tuesday
)
[1] => stdClass Object
(
[event_day] => Wednesday
)
[2] => stdClass Object
(
[event_day] => Friday
)
)
通过这种方式,您可以对任何事情进行排序,而不仅仅是几天。
答案 1 :(得分:1)
使用usort
和array_search
函数的解决方案:
// predefined weekdays list (in order)
$weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
// $arr is your initial array
usort($arr, function($a, $b) use($weekdays){
return array_search($a->event_day, $weekdays) - array_search($b->event_day, $weekdays);
});
print_r($arr);