按对象字段对对象数组进行排序 [英] Sort array of objects by object fields

查看:60
本文介绍了按对象字段对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
        )

   ....

推荐答案

使用 usort,这里有一个改编自手册的例子:

Use usort, here's an example adapted from the manual:

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

usort($your_data, "cmp");

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

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
    

  • 使用箭头函数(来自 PHP 7.4)

  • Using arrow functions (from PHP 7.4)

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

  • 此外,如果您要比较数值,fn($a, $b) =>$a->count - $b->count 作为比较"函数应该可以解决问题,或者,如果您想要另一种方式来做同样的事情,从 PHP 7 开始,您可以使用 Spaceship operator,像这样:fn($a, $b) =>$a->count <=>;$b->count.

    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.

    这篇关于按对象字段对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆