按一个属性对对象数组进行排序

发布于 2024-10-04 07:34:51 字数 529 浏览 6 评论 0原文

如何按其中一个字段(例如 namecount)对这个对象数组进行排序?

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
        )

   ....

How can I sort this array of objects by one of its fields, like name or 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
        )

   ....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

海之角 2024-10-11 07:34:51

使用 usort 自定义比较函数。以下是改编自手册的示例:

function cmp($a, $b) {
    return strcmp($a->name, $b->name);
}

usort($your_data, "cmp");

您还可以使用任何 callable 作为第二个参数。以下是一些示例:

  • 使用匿名函数(从 PHP 5.3 开始) )

     usort($your_data, function($a, $b) {
          return strcmp($a->名称, $b->名称);
      });
    
  • 从类内部

     usort($your_data, array($this, "cmp")); // “cmp”应该是类中的一个方法
    
  • 使用箭头函数(从 PHP 7.4 开始)

     usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));
    

此外,如果您要比较数值,fn($a, $b) =>; $a->count - $b->count 作为“比较”函数应该可以解决问题,或者,如果您想要另一种方法来完成同样的事情,从 PHP 7 开始,您可以使用宇宙飞船操作员,像这样: fn($a, $b) => $a->count <=>; $b->计数

Use usort to customize the comparison function. Here's an example adapted from the manual:

function cmp($a, $b) {
    return strcmp($a->name, $b->name);
}

usort($your_data, "cmp");

You can also use any callable as 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));
    

Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count as the "compare" function should do the trick, or, if you want yet another way of doing the same thing, starting from PHP 7 you can use the Spaceship operator, like this: fn($a, $b) => $a->count <=> $b->count.

☆獨立☆ 2024-10-11 07:34:51

这是使用闭包的更好方法

usort($your_data, function($a, $b)
{
    return strcmp($a->name, $b->name);
});

请注意,这不在 PHP 文档中,但如果您使用 5.3+ 则支持闭包,其中可以提供可调用参数。

Here's 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.

猫腻 2024-10-11 07:34:51

如果您想对整数值进行排序:

// Desc sort
usort($array,function($first,$second){
    return $first->number < $second->number;
});

// Asc sort
usort($array,function($first,$second){
    return $first->number > $second->number;
});

更新
使用字符串不要忘记转换为相同的寄存器(高位或低位)

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

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

UPDATED
with 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);
});
命硬 2024-10-11 07:34:51

如果您使用 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')); 

if you're using php oop you might need to change to:

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')); 
滥情稳全场 2024-10-11 07:34:51
usort($array, 'my_sort_function');

var_dump($array);

function my_sort_function($a, $b)
{
    return $a->name < $b->name;
}

count 字段将使用相同的代码。

有关 usort 的更多详细信息:https://www.php.net/usort

顺便说一句,你从哪里得到这个数组?我希望不是来自数据库?

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.

More details about usort: https://www.php.net/usort

Btw, where did you get that array from? I hope that not from database?

亚希 2024-10-11 07:34:51

要对一列值进行排序,array_column()array_multisort() 的组合是一种明智的方法。 Demo

array_multisort(array_column($array, 'count'), $array);

或者仅使用 spaceship 运算符调用 usort() 来执行更少的迭代设想。 Demo

usort($array, fn($a, $b) => $a->count <=> $b->count);

请注意,虽然计数值在输入数组中被转换为字符串类型值,但这两个排序函数都会正确地对按数字顺序排列值,而不是按字母顺序排列(错误地将 23420 放在 420 之前)。这是一个可靠的默认功能。

即使您可变地声明要排序的列,这两种方法都允许在不使用任何附加技术的情况下使用变量。

带变量的多排序演示

$property = 'count';
array_multisort(array_column($array, $property), $array);

带变量的 Usort 演示

$property = 'count';
usort($array, fn($a, $b) => $a->$property <=> $b->$property);

两个原生排序函数都是通过引用进行修改的,因此不要尝试通过返回值来访问已排序的数组。

array_multisort() 的默认排序方向是升序,因此在两个数组参数之间显式使用 SORT_ASC 没有任何好处。如果需要降序排序,请在两个数组之间写入 SORT_DESC (作为第二个参数)。

当自定义函数体将 $a 数据放在 spaceship 运算符的左侧并将 $b 数据放在 spaceship 运算符的左侧时,usort() 将以升序排序右侧。如果要按降序排序,只需在左侧写入 $b 数据,在右侧写入 $a 数据即可。

两种方法都能够接收多个排序规则,但因为这个问题只要求对单个列进行排序,所以该指南在这里是不合适的。

排序时在每次迭代时调用函数(如 strcmp())会降低效率。这不再是最佳实践。也不是使用双向比较(如 ><)来返回布尔结果。 usort() 预计会进行三向比较。

对于使用多个规则/列/属性对数据进行排序,此答案提供了很好的指导。

To sort on one column of values, a combination of array_column() and array_multisort() is one sensible way. Demo

array_multisort(array_column($array, 'count'), $array);

Or only call upon usort() with the spaceship operator to perform less iterating in this scenario. Demo

usort($array, fn($a, $b) => $a->count <=> $b->count);

Notice that although the count values are cast as string type values in the input array, both sorting functions will correctly sort the values numerically instead of alphabetizing them (erroneously putting 23420 before 420). This is a reliable default feature.

Even if you are variably declaring the column to sort on, both approaches allow the variable to be used without any addition techniques.

Multisort Demo with variable

$property = 'count';
array_multisort(array_column($array, $property), $array);

Usort Demo with variable

$property = 'count';
usort($array, fn($a, $b) => $a->$property <=> $b->$property);

Both native sorting functions modify by reference, so do not try to access the sorted array by their return value.

array_multisort()'s default sorting direction is ascending, so it is of no benefit to explicitly use the SORT_ASC between the two array parameters. If descending sorting is desired, write SORT_DESC between the two arrays (as the second parameter).

usort() will sort ascending when the custom function body puts $a data on the left side of the spaceship operator and $b data on the right side. For sorting in a descending direction, just write $b data on the left and $a data on the right.

Both approaches are capable of receiving multiple sorting rules, but because this question only asks to sort on a single column, that guidance is inappropriate here.

It will be less efficient to call a function (like strcmp()) on every iteration while sorting. This is no longer best practice. Neither is using a two-way comparison (like > or <) to return a boolean outcome. A three-way comparison is expected from usort().

For sorting data with multiple rules/columns/properties, this answer gives good guidance.

池木 2024-10-11 07:34:51

如果一切都失败了,这里还有另一种解决方案:

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

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;
一场信仰旅途 2024-10-11 07:34:51

您可以使用此函数(适用于 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;

        });
    }
}

示例:

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)

You can use this function (works in PHP Version >= 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)
宛菡 2024-10-11 07:34:51

您可以使用usort,如下所示:

usort($array,function($first,$second){
    return strcmp($first->name, $second->name);
});

You can use usort, like this:

usort($array,function($first,$second){
    return strcmp($first->name, $second->name);
});
只为守护你 2024-10-11 07:34:51

如果你想对日期进行排序

   usort($threads,function($first,$second){
        return strtotime($first->dateandtime) < strtotime($second->dateandtime);
    });

if you want to sort dates

   usort($threads,function($first,$second){
        return strtotime($first->dateandtime) < strtotime($second->dateandtime);
    });
ㄖ落Θ余辉 2024-10-11 07:34:51

这里所有答案的缺点是它们使用静态字段名称,所以我以 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;
    }
} 

Downside of all answers here is that they use static field 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.

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;
    }
} 
晚雾 2024-10-11 07:34:51

如果需要基于本地的字符串比较,可以使用 strcoll 而不是 strcmp

请记住首先使用 setlocaleLC_COLLATE 以根据需要设置区域设置信息。

  usort($your_data,function($a,$b){
    setlocale (LC_COLLATE, 'pl_PL.UTF-8'); // Example of Polish language collation
    return strcoll($a->name,$b->name);
  });

If you need local based string comparison, you can use strcoll instead of strcmp.

Remeber to first use setlocale with LC_COLLATE to set locale information if needed.

  usort($your_data,function($a,$b){
    setlocale (LC_COLLATE, 'pl_PL.UTF-8'); // Example of Polish language collation
    return strcoll($a->name,$b->name);
  });
三岁铭 2024-10-11 07:34:51

一个简单的替代方案,允许您动态确定排序所基于的字段:

$order_by = 'name';
usort($your_data, function ($a, $b) use ($order_by)
{
    return strcmp($a->{$order_by}, $b->{$order_by});
});

这基于 闭包类,允许匿名函数。它从 PHP 5.3 开始可用。

A simple alternative that allows you to determine dynamically the field on which the sorting is based:

$order_by = 'name';
usort($your_data, function ($a, $b) use ($order_by)
{
    return strcmp($a->{$order_by}, $b->{$order_by});
});

This is based on the Closure class, which allows anonymous functions. It is available since PHP 5.3.

愛上了 2024-10-11 07:34:51

如果您在 Codeigniter 中使用它,您可以使用以下方法:

usort($jobs, array($this->job_model, "sortJobs"));  // function inside Model
usort($jobs, array($this, "sortJobs")); // Written inside Controller.

@rmooney 谢谢您的建议。这真的对我有帮助。

If you are using this inside Codeigniter, you can use the methods:

usort($jobs, array($this->job_model, "sortJobs"));  // function inside Model
usort($jobs, array($this, "sortJobs")); // Written inside Controller.

@rmooney thank you for the suggestion. It really helps me.

找回味觉 2024-10-11 07:34:51

感谢您的启发,我还必须添加一个外部 $translator 参数

usort($listable_products, function($a, $b) {
    global $translator;
    return strcmp($a->getFullTitle($translator), $b->getFullTitle($translator));
});

Thanks for the inspirations, I also had to add an external $translator parameter

usort($listable_products, function($a, $b) {
    global $translator;
    return strcmp($a->getFullTitle($translator), $b->getFullTitle($translator));
});
同展鸳鸯锦 2024-10-11 07:34:51

如果您只需要按一个字段进行排序,那么 usort 是一个不错的选择。但是,如果您需要按多个字段排序,解决方案很快就会变得混乱。在这种情况下,可以使用 YaLinqo 库*,它为数组和对象实现类似 SQL 的查询语法。它对于所有情况都有一个漂亮的语法:

$sortedByName         = from($objects)->orderBy('$v->name');
$sortedByCount        = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');

这里,'$v->count'function ($v) { return $v->count; 的简写。 }(都可以使用)。这些方法链返回迭代器,但如果需要,您可以通过在末尾添加 ->toArray() 来获取数组。

* 由我开发

If you need to sort by only one field, then usort is a good choice. However, the solution quickly becomes messy if you need to sort by multiple fields. In this case, YaLinqo library* can be used, which implements SQL-like query syntax for arrays and objects. It has a pretty syntax for all cases:

$sortedByName         = from($objects)->orderBy('$v->name');
$sortedByCount        = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');

Here, '$v->count' is a shorthand for function ($v) { return $v->count; } (either can be used). These method chains return iterators, but you can get arrays by adding ->toArray() in the end if you need it.

* developed by me

孤千羽 2024-10-11 07:34:51

您可以使用 sorted 函数Nspl

use function \nspl\a\sorted;
use function \nspl\op\propertyGetter;
use function \nspl\op\methodCaller;

// Sort by property value
$sortedByCount = sorted($objects, propertyGetter('count'));

// Or sort by result of method call
$sortedByName = sorted($objects, methodCaller('getName'));

You can use sorted function from Nspl:

use function \nspl\a\sorted;
use function \nspl\op\propertyGetter;
use function \nspl\op\methodCaller;

// Sort by property value
$sortedByCount = sorted($objects, propertyGetter('count'));

// Or sort by result of method call
$sortedByName = sorted($objects, methodCaller('getName'));
东风软 2024-10-11 07:34:51

这就是我的实用程序类

class Util
{
    public static function sortArrayByName(&$arrayToSort, $meta) {
        usort($arrayToSort, function($a, $b) use ($meta) {
            return strcmp($a[$meta], $b[$meta]);
        });
    }
}

调用它:

Util::sortArrayByName($array, "array_property_name");

This is what I have for a utility class

class Util
{
    public static function sortArrayByName(&$arrayToSort, $meta) {
        usort($arrayToSort, function($a, $b) use ($meta) {
            return strcmp($a[$meta], $b[$meta]);
        });
    }
}

Call it:

Util::sortArrayByName($array, "array_property_name");
╄→承喏 2024-10-11 07:34:51

你可以像这样使用usort

如果你想按数字排序:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

或者 Abc char:

function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

查看更多:https://www.php.net/manual/en/function.usort.php

You can use usort like this

If you want to sort by number:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

Or Abc char:

function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

See more: https://www.php.net/manual/en/function.usort.php

半步萧音过轻尘 2024-10-11 07:34:51
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));
梦罢 2024-10-11 07:34:51

Demodave吃多键参考答案

 function array_sort_by(array $arr, $keys){

    if(!is_array($keys))
        $keyList = explode(',', $keys);
    $keyList = array_keys(array_flip($keyList)); // array_unique 
    $keyList = array_reverse($keyList);

    $result = &$arr;
    foreach ($keyList as $key) {
        if(array_key_exists($key, $arr))
            $result = usort($result, function($a, $b) use ($key) { return strcmp($a->{$key}, $b->{$key}); });
    }
    return $result;
}

reference answer of Demodave to eating multi key

 function array_sort_by(array $arr, $keys){

    if(!is_array($keys))
        $keyList = explode(',', $keys);
    $keyList = array_keys(array_flip($keyList)); // array_unique 
    $keyList = array_reverse($keyList);

    $result = &$arr;
    foreach ($keyList as $key) {
        if(array_key_exists($key, $arr))
            $result = usort($result, function($a, $b) use ($key) { return strcmp($a->{$key}, $b->{$key}); });
    }
    return $result;
}
不离久伴 2024-10-11 07:34:51

用这个....

$array_list = [
    "Apple" => 2,
    "Pear" => 1,
    "Orange" => 5,
    "Lemon" => 1,
    "Strawberry" => 2,
    "Banana" => 3
];

function cmp($a, $b) {
    return $b - $a;
}

$ao = new ArrayObject($object);
$ao->uasort('cmp');
print_r(json_encode($ao));

再见!!!!

use this....

$array_list = [
    "Apple" => 2,
    "Pear" => 1,
    "Orange" => 5,
    "Lemon" => 1,
    "Strawberry" => 2,
    "Banana" => 3
];

function cmp($a, $b) {
    return $b - $a;
}

$ao = new ArrayObject($object);
$ao->uasort('cmp');
print_r(json_encode($ao));

Bye!!!!

殤城〤 2024-10-11 07:34:51

就我而言,以下是我如何继续按对象字段对对象数组进行排序:

代码:(演示) -- 按last_name ASC 排序,然后first_name ASC

<?php

$array = array(
    (object)array(
        'first_name' => 'Léa',
        'last_name' => 'Weber',
    ),
    (object)array(
        'first_name' => 'Alexandre',
        'last_name' => 'Dupont',
    ),
    (object)array(
        'first_name' => 'Léa',
        'last_name' => 'Zotal',
    ),
    (object)array(
        'first_name' => 'Jérémie',
        'last_name' => 'Hoffmann',
    )
);

usort($array, function($a, $b) {
    return [$a->last_name, $a->first_name]
           <=>
           [$b->last_name, $b->first_name];
});


var_export($array);

输出:

array (
  0 => 
  (object) array(
     'first_name' => 'Alexandre',
     'last_name' => 'Dupont',
  ),
  1 => 
  (object) array(
     'first_name' => 'Jérémie',
     'last_name' => 'Hoffmann',
  ),
  2 => 
  (object) array(
     'first_name' => 'Léa',
     'last_name' => 'Weber',
  ),
  3 => 
  (object) array(
     'first_name' => 'Léa',
     'last_name' => 'Zotal',
  ),
)

PHP7.4 及更高版本的箭头语法。
使用宇宙飞船运算符 (<=>)(又名“组合比较运算符”或“三向比较运算符”)使多列排序变得超级简单。

资源: https://wiki.php.net/rfc/combined-comparison-operator< /a>
https://stackoverflow.com/a/54647220/18090932

For my part, here is how I proceeded to sort an array of objects by object fields:

Code: (Demo) -- sorts by last_name ASC, then first_name ASC

<?php

$array = array(
    (object)array(
        'first_name' => 'Léa',
        'last_name' => 'Weber',
    ),
    (object)array(
        'first_name' => 'Alexandre',
        'last_name' => 'Dupont',
    ),
    (object)array(
        'first_name' => 'Léa',
        'last_name' => 'Zotal',
    ),
    (object)array(
        'first_name' => 'Jérémie',
        'last_name' => 'Hoffmann',
    )
);

usort($array, function($a, $b) {
    return [$a->last_name, $a->first_name]
           <=>
           [$b->last_name, $b->first_name];
});


var_export($array);

Outpout:

array (
  0 => 
  (object) array(
     'first_name' => 'Alexandre',
     'last_name' => 'Dupont',
  ),
  1 => 
  (object) array(
     'first_name' => 'Jérémie',
     'last_name' => 'Hoffmann',
  ),
  2 => 
  (object) array(
     'first_name' => 'Léa',
     'last_name' => 'Weber',
  ),
  3 => 
  (object) array(
     'first_name' => 'Léa',
     'last_name' => 'Zotal',
  ),
)

Arrow syntax with PHP7.4 and higher.
Makes sorting by multiple columns SUPER easy with the spaceship operator (<=>) aka the "Combined Comparison Operator" or "Three-way Comparison Operator".

Resource: https://wiki.php.net/rfc/combined-comparison-operator
https://stackoverflow.com/a/54647220/18090932

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文