php 按对象字段对对象数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4282413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort array of objects by object fields
提问by Alex
How can I sort this array of objects by one of its fields, like name
or count
?
如何按其字段之一对对象数组进行排序,例如name
或count
?
Array
(
[0] => stdClass Object
(
[ID] => 1
[name] => Mary Jane
[count] => 420
)
[1] => stdClass Object
(
[ID] => 2
[name] => Johnny
[count] => 234
)
[2] => stdClass Object
(
[ID] => 3
[name] => Kathy
[count] => 4354
)
....
回答by cambraca
Use usort, here's an example adapted from the manual:
使用usort,这里有一个改编自手册的例子:
function cmp($a, $b) {
return strcmp($a->name, $b->name);
}
usort($your_data, "cmp");
You can also use any callableas the second argument. Here are some examples:
您还可以使用任何可调用对象作为第二个参数。这里有些例子:
Using anonymous functions(from PHP 5.3)
usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);});
From inside a class
usort($your_data, array($this, "cmp")); // "cmp" should be a method in the class
Using arrow functions(from PHP 7.4)
usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));
使用匿名函数(来自 PHP 5.3)
usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);});
从班级内部
usort($your_data, array($this, "cmp")); // "cmp" should be a method in the class
使用箭头函数(来自 PHP 7.4)
usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));
Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count
as the "compare" function should do the trick.
此外,如果您要比较数值,fn($a, $b) => $a->count - $b->count
则“比较”函数应该可以解决问题。
回答by Scott Quinlan
Heres a nicer way using closures
这是使用闭包的更好方法
usort($your_data, function($a, $b)
{
return strcmp($a->name, $b->name);
});
Please note this is not in PHP's documentation but if you using 5.3+ closures are supported where callable arguments can be provided.
请注意,这不在 PHP 的文档中,但如果您使用 5.3+ 闭包,则可以提供可调用参数。
回答by Roman Yakoviv
If you want to sort integer values:
如果要对整数值进行排序:
// Desc sort
usort($array,function($first,$second){
return $first->number < $second->number;
});
// Asc sort
usort($array,function($first,$second){
return $first->number > $second->number;
});
UPDATEDwith the string don't forget to convert to the same register (upper or lower)
用字符串更新不要忘记转换为相同的寄存器(上或下)
// Desc sort
usort($array,function($first,$second){
return strtolower($first->text) < strtolower($second->text);
});
// Asc sort
usort($array,function($first,$second){
return strtolower($first->text) > strtolower($second->text);
});
回答by Doron Segal
if you're using php oop you might need to change to:
如果您使用的是 php oop,则可能需要更改为:
public static function cmp($a, $b)
{
return strcmp($a->name, $b->name);
}
//in this case FUNCTION_NAME would be cmp
usort($your_data, array('YOUR_CLASS_NAME','FUNCTION_NAME'));
回答by zerkms
usort($array, 'my_sort_function');
var_dump($array);
function my_sort_function($a, $b)
{
return $a->name < $b->name;
}
The same code will be with the count
field.
相同的代码将用于该count
字段。
More details about usort
: http://ru2.php.net/usort
有关更多详细信息usort
:http: //ru2.php.net/usort
Btw, where did you get that array from? I hope that not from database?
顺便说一句,你从哪里得到这个数组?我希望不是来自数据库?
回答by PoengAlex
You can use this function (works in PHP Version >= 5.3):
您可以使用此功能(适用于 PHP 版本 >= 5.3):
function sortArrayByKey(&$array,$key,$string = false,$asc = true){
if($string){
usort($array,function ($a, $b) use(&$key,&$asc)
{
if($asc) return strcmp(strtolower($a{$key}), strtolower($b{$key}));
else return strcmp(strtolower($b{$key}), strtolower($a{$key}));
});
}else{
usort($array,function ($a, $b) use(&$key,&$asc)
{
if($a[$key] == $b{$key}){return 0;}
if($asc) return ($a{$key} < $b{$key}) ? -1 : 1;
else return ($a{$key} > $b{$key}) ? -1 : 1;
});
}
}
Example:
例子:
sortArrayByKey($yourArray,"name",true); //String sort (ascending order)
sortArrayByKey($yourArray,"name",true,false); //String sort (descending order)
sortArrayByKey($yourArray,"id"); //number sort (ascending order)
sortArrayByKey($yourArray,"count",false,false); //number sort (descending order)
回答by Luca C.
You can use usort
, like this:
你可以使用usort
,像这样:
usort($array,function($first,$second){
return strcmp($first->name, $second->name);
});
回答by Adrian P.
If everything fails here is another solution:
如果一切都失败了,这是另一种解决方案:
$names = array();
foreach ($my_array as $my_object) {
$names[] = $my_object->name; //any object field
}
array_multisort($names, SORT_ASC, $my_array);
return $my_array;
回答by oshell
Downside of all answers here is that they use staticfield names, so I wrote an adjusted version in OOP style. Assumed you are using getter methods you could directly use this Class and use the field name as parameter. Probably someone find it useful.
这里所有答案的缺点是它们使用静态字段名称,所以我用 OOP 风格编写了一个调整版本。假设您正在使用 getter 方法,您可以直接使用此类并将字段名称用作参数。可能有人觉得它有用。
class CustomSort{
public $field = '';
public function cmp($a, $b)
{
/**
* field for order is in a class variable $field
* using getter function with naming convention getVariable() we set first letter to uppercase
* we use variable variable names - $a->{'varName'} would directly access a field
*/
return strcmp($a->{'get'.ucfirst($this->field)}(), $b->{'get'.ucfirst($this->field)}());
}
public function sortObjectArrayByField($array, $field)
{
$this->field = $field;
usort($array, array("Your\Namespace\CustomSort", "cmp"));;
return $array;
}
}
回答by Nicolas Giszpenc
if you want to sort dates
如果你想对日期进行排序
usort($threads,function($first,$second){
return strtotime($first->dateandtime) < strtotime($second->dateandtime);
});