-1

I need to sort this array below, in descending order, but I'm currently stuck and can't think of a simple solution.

This is the array structure:

$data = Array
(
    [Name1] => Array
        (
            [1] => 40-45
            [0] => 124791.63
        )

    [Name2] => Array
        (
            [1] => 46
            [0] => 2624.7
        )

    [Name3] => Array
        (
            [1] => 50
            [0] => 37784.27
        )

    [Name4] => Array
        (
            [1] => 52
            [0] => 1008
        )
)

I want to sort it by value $data[Name1][0], in the descending order, as you can see the current array is not sorted since the values go like this:

124791.63 -- 2624.7 -- 37784.27 ...etc

Is there any simple solution to this? I googled, but I couldn't find an answer to this specific problem.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    This has been asked quite a bit... have you looked at the other questions about 'sorting multidimensional array' and found they did not work out how you need? – IncredibleHat Oct 30 '17 at 22:15
  • `array_multisort($data, array_column($data, 0))` should do it. Or give you a few more functions to search for. – jh1711 Oct 30 '17 at 22:17
  • Crazy the number of duplicates on that question, search if your friend! (can't flag no more today :-0 – Nic3500 Oct 30 '17 at 22:42

1 Answers1

0

An option to do this is use uasort.

For example:

$data = [
    'Name1' => [
        "124791.63",
        "40-45"
    ],
    'Name2' => [
        "2624.7",
        "46"
    ],
    'Name3' => [
        "37784.27",
        "50"
    ],
    'Name4' => [
        "1008",
        "52"
    ]
];


function sortByValue($a, $b) {
    return $a[0] < $b[0];
}

uasort($data, 'sortByValue');

echo "<pre>";
print_r($data);

Will result in:

Array
(
    [Name1] => Array
        (
            [0] => 124791.63
            [1] => 40-45
        )

    [Name3] => Array
        (
            [0] => 37784.27
            [1] => 50
        )

    [Name2] => Array
        (
            [0] => 2624.7
            [1] => 46
        )

    [Name4] => Array
        (
            [0] => 1008
            [1] => 52
        )

)
The fourth bird
  • 154,723
  • 16
  • 55
  • 70