php - 如何在 PHP 中按值对对象进行排序?
问题描述
我正在检索 JSON 中的时间表,它工作正常。
但是,我想按 timetable_session->name 对结果进行排序
首先是公共游泳 其次是室内游泳池 最后是泳道游泳
任何其他人都会在这些之后出现。
有人能指出我正确的方向吗?
[1]=>
object(stdClass)#1924 (11) {
["id"]=>
int(2569543)
["start_time"]=>
string(5) "06:00"
["end_time"]=>
string(5) "07:15"
["facility_name"]=>
string(13) "Swimming Pool"
["date"]=>
string(10) "2018-07-20"
["day"]=>
string(6) "Friday"
["term_type"]=>
object(stdClass)#1925 (2) {
["id"]=>
int(1)
["name"]=>
string(6) "Normal"
}
["is_cancelled"]=>
bool(false)
["timetable_session"]=>
object(stdClass)#1923 (2) {
["id"]=>
int(35531)
["name"]=>
string(13) "Lane Swimming"
}
["facility"]=>
object(stdClass)#1922 (4) {
["id"]=>
int(70912)
["length"]=>
float(25)
["primary_name"]=>
string(13) "Swimming Pool"
["facility_type"]=>
object(stdClass)#1916 (2) {
["id"]=>
int(31)
["name"]=>
string(11) "Indoor Pool"
}
}
["lanes"]=>
string(1) "3"
}
[2]=>
object(stdClass)#1919 (11) {
["id"]=>
int(2569529)
["start_time"]=>
string(5) "06:00"
["end_time"]=>
string(5) "10:30"
["facility_name"]=>
string(13) "Swimming Pool"
["date"]=>
string(10) "2018-07-20"
["day"]=>
string(6) "Friday"
["term_type"]=>
object(stdClass)#1920 (2) {
["id"]=>
int(1)
["name"]=>
string(6) "Normal"
}
["is_cancelled"]=>
bool(false)
["timetable_session"]=>
object(stdClass)#1918 (2) {
["id"]=>
int(35541)
["name"]=>
string(15) "Public Swimming"
}
["facility"]=>
object(stdClass)#1917 (4) {
["id"]=>
int(70912)
["length"]=>
float(25)
["primary_name"]=>
string(13) "Swimming Pool"
["facility_type"]=>
object(stdClass)#1911 (2) {
["id"]=>
int(31)
["name"]=>
string(11) "Indoor Pool"
}
}
["lanes"]=>
string(1) "3"
}
[3]=>
object(stdClass)#1914 (11) {
["id"]=>
int(2569536)
["start_time"]=>
string(5) "07:15"
["end_time"]=>
string(5) "08:00"
["facility_name"]=>
string(13) "Swimming Pool"
["date"]=>
string(10) "2018-07-20"
["day"]=>
string(6) "Friday"
["term_type"]=>
object(stdClass)#1915 (2) {
["id"]=>
int(1)
["name"]=>
string(6) "Normal"
}
["is_cancelled"]=>
bool(false)
["timetable_session"]=>
object(stdClass)#1913 (2) {
["id"]=>
int(35581)
["name"]=>
string(9) "Swimfit®"
}
["facility"]=>
object(stdClass)#1912 (4) {
["id"]=>
int(70912)
["length"]=>
float(25)
["primary_name"]=>
string(13) "Swimming Pool"
["facility_type"]=>
object(stdClass)#1906 (2) {
["id"]=>
int(31)
["name"]=>
string(11) "Indoor Pool"
}
}
["lanes"]=>
string(1) "1"
}
解决方案
usort 允许您传递定义您自己的排序算法的闭包。
usort($array, function($a,$b) {
return strcmp($a->timetable_session->name, $b->timetable_session->name);
});
看起来您不想要标准的字符串比较,因此您必须为此定义自己的算法,但这应该可以帮助您入门。
推荐阅读
- java - 无法在 Java 中更改日历 DAY_OF_MONTH
- sql - 是否有任何 RDBMS 提供预准备语句的功能?
- mongodb - 聚合无效运算符'$switch'
- javascript - performance.now() 是否从 navigationStart 开始?
- c++ - 如何使用 boost::asio 从 UDP 端口接收广播数据包和发送数据
- rule - SonarLint 规则中的“squid:”前缀是什么意思?
- kubernetes - 调用执行器刷新端点时,所有 kubernetes pod 配置都不会刷新
- python - 在熊猫中检查相同的行并有条件地创建新列
- emacs - 如何在 Emacs 25 中将 Cx SPC 本地绑定到 gud 模式
- sql - 在三个连接表中计数