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

时间:2014-05-30 12:31:56

标签: php

我有这样一个数组,我需要能够按键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
        )
)

IE,如果客户端将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
        )
)

这是怎么做到的?

2 个答案:

答案 0 :(得分:1)

我没有测试过这个 - 但它应该很接近。

有这两个功能

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));

Example #4 on php.net should give you further help as well

答案 1 :(得分:0)

试试这个。

$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' );