这篇文章主要介绍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按对象字段对对象数组进行排序的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!