如何在按另一个键排序之前按键对 PHP 数组进行分组?

How to group PHP arrays by key before sorting by another key?

我有一个包含键 countedplacement 的数组,我试图在排序之前对其进行分组。该数组应首先按 counted 排序,然后,对于每个重复项 counted,然后应按 placement.

排序
$array = [
    [
        'id' => 1,
        'placement' => 8,
        'counted' => 3
        'user' => ['name' => 'foo'],
    ],
    [
        'id' => 2,
        'placement' => 5,
        'counted' => 3
        'user' => ['name' => 'bar'],
    ],
    [
        'id' => 3,
        'placement' => 1,
        'counted' => 2
        'user' => ['name' => 'foobar'],
    ]
];

我在这里的预期输出是:

$array = [
    [
        'id' => 2,
        'placement' => 5,
        'counted' => 3
        'user' => ['name' => 'bar'],
    ],
    [
        'id' => 1,
        'placement' => 8,
        'counted' => 3
        'user' => ['name' => 'foo'],
    ],
    [
        'id' => 3,
        'placement' => 1,
        'counted' => 2
        'user' => ['name' => 'foobar'],
    ]
];

我已经尝试usort实现这个:

usort($array, fn($a, $b) => ((int)$a['placement'] <=> (int)$b['counted']) * -1);

但这给了我意想不到的结果。我尝试的一切似乎都不起作用,任何想法将不胜感激。

如果不在意效率,可以这样写

collect($array)
    ->sortByDesc('counted')
    ->groupBy('counted')
    ->map(function ($group) {
        return $group->sortBy('placement');
    })
    ->flatten(1)
    ->toArray()

因为你更喜欢使用 usort 所以这就是我的答案

$array = [
    [
        'id' => 1,
        'placement' => 8,
        'counted' => 3,
        'user' => ['name' => 'foo'],
    ],
    [
        'id' => 2,
        'placement' => 5,
        'counted' => 3,
        'user' => ['name' => 'bar'],
    ],
    [
        'id' => 3,
        'placement' => 1,
        'counted' => 2,
        'user' => ['name' => 'foobar'],
    ]
];


usort($array, function ($a, $b) {
    if ($a['counted'] < $b['counted']) {
        return 1;
    }

    if ($a['counted'] === $b['counted'] && $a['placement'] > $b['placement']) {
        return 1;
    }
});