这篇文章主要介绍PHP按对象字段对对象数组进行排序的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
目前创新互联已为数千家的企业提供了网站建设、域名、虚拟空间、网站托管运营、企业网站设计、青龙网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
按对象字段对对象数组排序的实现方法;
给定一个对象数组,我们按对象和给定字段对数组排序。
方法:
usort()函数是PHP中内置的函数,用于使用给定的比较器函数对元素数组进行有条件的排序。usort()函数还可以用于按对象字段对对象数组排序。调用usort()函数,第一个参数作为对象数组,第二个参数作为比较器函数,必须在此基础上比较两个数组对象。
PHP代码示例:
'100', 'name' => 'Sam', 'subject' => 'Data Structures' ), array( 'score' => '50', 'name' => 'Tanya', 'subject' => 'Advanced Algorithms' ), array( 'score' => '75', 'name' => 'Jack', 'subject' => 'Distributed Computing' ) ); class geekSchool { var $score, $name, $subject; public function geekSchool($data) { $this->name = $data['name']; $this->score = $data['score']; $this->subject = $data['subject']; } } function data2Object($data) { $class_object = new geekSchool($data); return $class_object; } function comparator($object1, $object2) { return $object1->score > $object2->score; } $school_data = array_map('data2Object', $gfg_array); print("原始对象数组:\n"); print_r($school_data); usort($school_data, 'comparator'); print("\n对象数组排序:\n"); print_r($school_data);
输出:
原始对象数组: Array ( [0] => geekSchool Object ( [score] => 100 [name] => Sam [subject] => Data Structures ) [1] => geekSchool Object ( [score] => 50 [name] => Tanya [subject] => Advanced Algorithms ) [2] => geekSchool Object ( [score] => 75 [name] => Jack [subject] => Distributed Computing ) ) 对象数组排序: Array ( [0] => geekSchool Object ( [score] => 50 [name] => Tanya [subject] => Advanced Algorithms ) [1] => geekSchool Object ( [score] => 75 [name] => Jack [subject] => Distributed Computing ) [2] => geekSchool Object ( [score] => 100 [name] => Sam [subject] => Data Structures ) )
以上是PHP按对象字段对对象数组进行排序的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!