在PHP中按对象值排序对象数组


Ordering an array of objects by object value in PHP

如果我有一个包含如下对象的数组:

Array
(
    [0] => stdClass Object
        (
            [img] => image1.jpg
            [order] => 1
        )
    [1] => stdClass Object
        (
            [img] => image2.jpg
            [order] => 3
        )
    [2] => stdClass Object
        (
            [img] => image3.jpg
            [order] => 2
        )
    [3] => stdClass Object
        (
            [img] => image4.jpg
            [order] => 4
        )
)

我怎么能排序数组对象的"顺序"值?在这种情况下,顺序应该是:image1.jpg, image3.jpg, image2.jpg, image4.jpg.

下面是您的代码示例:

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

usort($youArray, "sortImage");

编辑:在你的情况下,你有订单属性但PHP也可以比较"image1"answers"image2"字符串

PHP 5.3+

usort($myArray, function ($a, $b) {
    if ($a->order == $b->order) {
        return 0;
    }
    return ($a->order < $b->order) ? -1 : 1;
});

& lt;PHP 5.3只需将匿名函数更改为预定义的命名函数

你应该使用这个函数:http://php.net/manual/en/function.usort.php

您必须编写一个比较函数,作为usort的第二个参数。