我如何排序这个对象数组的一个字段,如名称或计数?

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
        )

   ....

当前回答

用这个……

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

再见! !

其他回答

你可以像这样使用我们

如果你想按数字排序:

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

你可以这样用usort:

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

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

用这个……

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

再见! !

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

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