在PHP中使用usort对对象数组进行排序? [英] Using usort in php to sort an array of objects?

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

问题描述

我确实看过usort,但还是有点困惑...

I did look at usort, but am still a little confused...

这是$ myobject对象的样子:

Here is what the $myobject object looks like:

Array
(
    [0] => stdClass Object
        (
            [tid] => 13
            [vid] => 4
        )

    [1] => stdClass Object
        (
            [tid] => 10
            [vid] => 4
        )

    [2] => stdClass Object
        (
            [tid] => 34
            [vid] => 4
        )

    [3] => stdClass Object
        (
            [tid] => 9
            [vid] => 4
        )

我看到了:

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

我正在尝试根据tid进行排序,但是,我想我不确定我是否真的必须将体重改变为某些东西?还是按原样工作?我尝试过,但是什么也没输出...

I'm trying to sort according to tid, but, I guess I'm just not sure really if I have to change weight to something? Or will it just work as is? I tried it, but nothing outputted...

推荐答案

cmp是usort用来对复杂对象(例如您的对象)进行比较以找出如何对其进行排序的回调函数.修改cmp以供您使用(或将其重命名为您想要的任何名称)

cmp is the a callback function that usort uses to compare complex objects (like yours) to figure out how to sort them. modify cmp for your use (or rename it to whatever you wish)

function cmp( $a, $b )
{ 
  if(  $a->tid ==  $b->tid ){ return 0 ; } 
  return ($a->tid < $b->tid) ? -1 : 1;
} 
usort($myobject,'cmp');

function sort_by_tid( $a, $b )
{ 
  if(  $a->tid ==  $b->tid ){ return 0 ; } 
  return ($a->tid < $b->tid) ? -1 : 1;
} 
usort($myobject,'sort_by_tid');

http://www.php.net/usort

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

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