Php 如何按对象键对包含对象的数组进行排序

Php 如何按对象键对包含对象的数组进行排序,php,Php,我有这样一个数组,我需要能够排序键ASC和DESC Array ( [0] => stdClass Object ( [id] => 2323 [regno] => 45101008785 [regdate] => 1993-03-26 ) [1] => stdClass Object ( [id] =&g

我有这样一个数组,我需要能够排序键ASC和DESC

Array
(
    [0] => stdClass Object
        (
            [id] => 2323
            [regno] => 45101008785
            [regdate] => 1993-03-26
        )

    [1] => stdClass Object
        (
            [id] => 2322
            [regno] => 49201003827
            [regdate] => 1992-04-08
        )

    [2] => stdClass Object
        (
            [id] => 2318
            [regno] => 240100720
            [regdate] => 1992-10-01
        )

    [3] => stdClass Object
        (
            [id] => 2317
            [regno] => 900100881
            [regdate] => 1992-12-28
        )
)
也就是说,如果客户端将GET参数设置为?sort_by=regno&type=asc,我需要通过PHP将其排序为:

Array
(

    [0] => stdClass Object
        (
            [id] => 2318
            [regno] => 240100720
            [regdate] => 1992-10-01
        )

    [1] => stdClass Object
        (
            [id] => 2317
            [regno] => 900100881
            [regdate] => 1992-12-28
        )

    [2] => stdClass Object
        (
            [id] => 2323
            [regno] => 45101008785
            [regdate] => 1993-03-26
        )

    [3] => stdClass Object
        (
            [id] => 2322
            [regno] => 49201003827
            [regdate] => 1992-04-08
        )
)

这是怎么做到的?

我还没有测试过这一点,但应该很接近

有这两个功能

function sorter($type, $key) 
{
    if ($type === 'asc')
    {
        return function ($a, $b) use ($key) {
            return strcmp($a->{$key}, $b->{$key});
        };
    }
    else
    {
        return function ($a, $b) use ($key) {
            return strcmp($b->{$key}, $a->{$key});
        };
    }
}
然后在代码中

usort($array, sorter($type, $sort_by));
试试这个

$arr = 'your_array';

function my_custom_sort( $a, $b ) {
   $cond = trim( $_GET[ 'sort_by' ] );
   $type = trim( $_GET[ 'type' ] );

   if( !isset( $a->{$cond} ) || !isset( $b->{$cond} ) ) {
     return 0;
   }

   // asc or desc
   $return = array( -1, 1 );
   switch( $type ) {
      case 'asc':
           $return = array( -1, 1 );
      case 'desc':
           $return = array( 1, -1 );
   }

   if( $a->{$cond} == $b->{$cond} ) {
      return 0;
   }

   return ($a->{$cond} < $b->{$cond}) ? $return[0] : $return[1];
}

usort( $arr, 'my_custom_sort' );
$arr='your_array';
函数my\u custom\u sort($a,$b){
$cond=trim($\u GET['sort\u by']);
$type=trim($_GET['type']);
if(!isset($a->{$cond})| |!isset($b->{$cond})){
返回0;
}
//asc或desc
$return=数组(-1,1);
交换机($类型){
案例“asc”:
$return=数组(-1,1);
案例“描述”:
$return=数组(1,-1);
}
如果($a->{$cond}==b->{$cond}){
返回0;
}
return($a->{$cond}<$b->{$cond})$return[0]:$return[1];
}
usort($arr,'我的自定义排序');

这很奇怪。拥有4k+代表,你应该知道如何搜索(或者至少知道如何提出好问题)或者至少知道如何对一系列对象进行排序。对不起,我有一个漫长的星期没有思考清楚。这已经被问了至少一千次了!!!