在PHP排序对象 [英] Sort Object in PHP

查看:85
本文介绍了在PHP排序对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是在PHP中的对象进行排序优雅的方式?我很想完成与此类似。

What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.

$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);

基本上指定我要排序的阵列,以及我要排序的字段。我看着多维数组排序,并有可能是那里的东西是有用的,但我没有看到任何优雅或显而易见的。

Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.

推荐答案

几乎一字不差:

function compare_weights($a, $b) { 
    if($a->weight == $b->weight) {
        return 0;
    } 
    return ($a->weight < $b->weight) ? -1 : 1;
} 

usort($unsortedObjectArray, 'compare_weights');

如果您希望对象能够自己解决,例如看这里3: http://php.net/usort

If you want objects to be able to sort themselves, see example 3 here: http://php.net/usort

这篇关于在PHP排序对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆