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

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

再见! !

其他回答

如果你想对日期排序

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

用这个……

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

再见! !

如果您只需要根据一个字段进行排序,那么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'是函数($v) {return $v->count;}(任何一个都可以使用)。这些方法链返回迭代器,但如果需要,可以在最后添加->toArray()来获得数组。

*由我开发

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

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