如何按这些对象键对包含对象的数组进行排序[复制]
问题描述:
This question already has an answer here:
I have such an array that I need to be able to sort by keys ASC and 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, if client sets GET parameters to ?sort_by=regno&type=asc, I need to sort this via PHP to:
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
)
)
How is this done?
</div>
答
I havent tested this - but it should be close.
Have these two functions
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});
};
}
}
Then in your code
usort($array, sorter($type, $sort_by));
答
Try this.
$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' );