在PHP中使用usort对对象数组进行排序?

在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