I am trying to sort a multidimensional array value based on a consistent key. My array looks something similar to this and the key I want to sort values in order by is discipline_one
.
$data = [
[
'id' => 1,
'score' => 200,
'results' => [
'discipline_one' => "4:01"
],
],
[
'id' => 2,
'score' => 250,
'results' => [
'discipline_one' => "3:50"
],
],
[
'id' => 3,
'score' => 284,
'results' => [
'discipline_one' => "3:42"
],
],
[
'id' => 4,
'score' => 300,
'results' => [
'discipline_one' => "4:27"
],
],
];
Going off the id
key in the above example, my expected output would be in the order:
3, 2, 1, 4
Previously, to query based on score
I used:
array_multisort(array_column($data, 'score'), SORT_DESC, $data);
However, if I add an additional array_column
on this for the discipline_one
consistent key then I get:
array_multisort(array_column(array_column($data, 'result'), 'discipline_one'), SORT_DESC, $data);
array_multisort(): Array sizes are inconsistent
The third argument expects the same array which in this case is not possible. Does any one know a way I can achieve this?
CodePudding user response:
Why not using simple usort
?
usort($data, fn($a, $b) => ($a['results']['discipline_one'] <=> $b['results']['discipline_one']) * -1);