Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a multi-dimensional array based on a consistent array key in PHP

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Why not using simple usort?

usort($data, fn($a, $b) => ($a['results']['discipline_one'] <=> $b['results']['discipline_one']) * -1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading