简体   繁体   English

如何在PHP中按对象字段对对象数组排序?

[英]How to sort an array of objects by object field in PHP?

I have an array of rows from MySQL query. 我有一个来自MySQL查询的行数组。 What I need to do is sort them by one of the fields (unsigned int type). 我需要做的是按一个字段(无符号int类型)对它们进行排序。 I looked through reference, but did not understand how exactly do I sort arrays of objects, because PHP does not seem to have something like operator overloading (what you do in C++), and some existing functions say they're unstable, meaning that with 2 equal elements their position in sorted array is undefined, which sounds really weird IMO. 我翻阅了一下参考资料,但不明白如何对对象数组进行精确排序,因为PHP似乎没有像运算符重载(在C ++中那样),并且某些现有函数表示它们不稳定,这意味着2个相等的元素在排序数组中的位置未定义,这听起来确实很怪异IMO。 So, what's the general approach in PHP when you need to sort an array of objects? 那么,当您需要对对象数组进行排序时,PHP的一般方法是什么?

You'll need to write your own function to do the comparison. 您需要编写自己的函数进行比较。 Once you have that function, you can then use usort - http://php.net/manual/en/function.usort.php 一旦有了该功能,就可以使用usort- http://php.net/manual/en/function.usort.php

Note that this also works with sorting an array of objects, you just have to change your comparison function. 请注意,这也适用于对对象数组进行排序,只需更改比较功能即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM