对象的数组排序按对象字段 [英] Sort array of objects by object fields
本文介绍了对象的数组排序按对象字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么可以排序这个数组对象由它的领域,一个像名称
或计数
?
阵列
(
[0] => stdClass的对象
(
[ID] => 1
[名] =>玛丽·简
[计] => 420
) [1] => stdClass的对象
(
[ID] => 2
[名] =>约翰尼
[计] => 234
) [2] => stdClass的对象
(
[ID] => 3
[名] =>凯西
[计] => 4354
) ....
解决方案
使用 usort ,这里是一个例如改编自手册:
函数CMP($ A,$ B)
{
返回STRCMP($ A->的名字,$ B->名);
}usort($ your_data,CMP);
的从进口评论编辑:的
如果你正在整理从类内部数组和你的排序功能 CMP
也定义在类内部,然后使用此:
usort($ your_data,阵列($此,CMP))
How can I sort this array of objects by one of its fields, like name
or count
?
Array
(
[0] => stdClass Object
(
[ID] => 1
[name] => Mary Jane
[count] => 420
)
[1] => stdClass Object
(
[ID] => 2
[name] => Johnny
[count] => 234
)
[2] => stdClass Object
(
[ID] => 3
[name] => Kathy
[count] => 4354
)
....
解决方案
Use usort, here's an example adapted from the manual:
function cmp($a, $b)
{
return strcmp($a->name, $b->name);
}
usort($your_data, "cmp");
edits imported from comments:
If you're sorting the array from inside the class and your sorting function cmp
is also defined inside the class, then use this:
usort($your_data, array($this, "cmp"))
这篇关于对象的数组排序按对象字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文