Home > Net >  PHP Sort Multi Dimensional Array Value - Not Sorting
PHP Sort Multi Dimensional Array Value - Not Sorting

Time:05-11

I have a multi dimensional array in PHP but it is not sorting correctly.

Here is my code:

$records = [
    [
        'project_id' => 3,
        'purchase_amount' => [
            'value' => 900000,
            'currency' => 'USD',
        ],
    ],
    [
        'project_id' => 1,
        'purchase_amount' => [
            'value' => 1000,
            'currency' => 'USD',
        ],
    ],
    [
        'project_id' => 2,
        'purchase_amount' => [
            'value' => 200,
            'currency' => 'USD',
        ],
    ],
    [
        'project_id' => 333,
        'purchase_amount' => [
            'value' => 9,
            'currency' => 'USD',
        ],
    ],
    [
        'project_id' => 366,
        'purchase_amount' => [
            'value' => 1,
            'currency' => 'USD',
        ],
    ],
];

# ==========
# sort the array | this will be in ascending order...
# ==========
usort($records, function ($a, $b) {
    return strcmp((int)$a['purchase_amount']['value'], (int)$b['purchase_amount']['value']);
});

Ends up with this result even though I am forcing the value to an integer.

It should be in numerical order such as: 1, 9, 200, 1000, 900000

What am I doing wrong? This is what I end up with ...

Array
(
    [0] => Array
        (
            [project_id] => 366
            [purchase_amount] => Array
                (
                    [value] => 1
                    [currency] => USD
                )

        )

    [1] => Array
        (
            [project_id] => 1
            [purchase_amount] => Array
                (
                    [value] => 1000
                    [currency] => USD
                )

        )

    [2] => Array
        (
            [project_id] => 2
            [purchase_amount] => Array
                (
                    [value] => 200
                    [currency] => USD
                )

        )

    [3] => Array
        (
            [project_id] => 333
            [purchase_amount] => Array
                (
                    [value] => 9
                    [currency] => USD
                )

        )

    [4] => Array
        (
            [project_id] => 3
            [purchase_amount] => Array
                (
                    [value] => 900000
                    [currency] => USD
                )

        )

)

CodePudding user response:

strcmp compare ASCII of every character of the strings, if not equal it will stop, so for strcmp, 200 is small than 9 cuz ASCII of 2 < ASCII of 9.

So in your case you should use

usort($records, function ($a, $b) {
    return $a['purchase_amount']['value'] > $b['purchase_amount']['value'] ? 1 : -1;
});
  • Related