使用强制类型转换按对象属性排序对象


usort objects by object property using casting

我有一个对象数组,其中具有我希望排序的属性id。此属性以字符串形式包含数字。我正在尝试将这些字符串转换为整型来对它们进行排序。

array(
    object(stdClass)#10717 (26) {
        ["id"]=>
            string(2) "12"
    },
    object(stdClass)#10718 (26) {
        ["id"]=>
            string(2) "13"
    }
    object(stdClass)#10719 (26) {
        ["id"]=>
            string(2) "8"
    }
 ...

我的代码如下

class Test 
{
    public static function test( $array ) {
        usort( $array, 'callBackSort')
        return $array;
    }
    function callBackSort( $a, $b ) {
        $a = $a->id;
        $a = (int)$a;
        $b = $b->id;
        $b = (int)$b;
        if ( $a == $b ) {
            return 0;
        }
        return ( $a < $b ) ? -1 : 1;
    }
}
// In another file
$array = Test::test($array);
var_dump( $array );

然而,这不起作用,数组没有排序(与原始数组没有区别)。我对usort完全陌生。

编辑:如果我从类中删除回调函数并将其放在与$array = Test::test($array);相同的文件中,那么它似乎可以工作。

我认为问题是您的ussort()函数试图从静态上下文中调用名为"callBackSort"的非静态方法。

保持你的callBackSort函数在同一个文件(类)作为"test"方法,使其静态和公共,保护或私有取决于你是否会在其他地方使用它,并通过传递一个数组作为第二个参数来调用它。

顺便说一下,你的callBackSort函数比它需要的要复杂一些。不需要将值强制转换为int来进行比较。
class Test 
{
    public static function test( $array ) {
        //this will call a static method called "callBackSort" from class "Test" - equivalent to calling Test::callBackSort()
        usort( $array, array("Test", "callBackSort"));
        return $array;
    }
    public static function callBackSort( $a, $b ) {
        if ( $a->id == $b->id ) {
            return 0;
        }
        return ( $a->id < $b->id ) ? -1 : 1;
    }
}

见下面类似情况的答案:在php中使用ussort与类私有函数