Search code examples
phparrayssorting

PHP - sort array by array key


I have this array in PHP:

In PHP APIs I have this array and want to sort ot by custom_price, but not getting how to acheive so ..

Array
(
    [0] => Array
        (
            [id] => 1204
            [custom_price] => 33.1500
        )


    [1] => Array
        (
            [id] => 1199
            [custom_price] => 16.83
        )

    [2] => Array
        (
            [id] => 1176
            [custom_price] => 16.83
        )

    [3] => Array
        (
            [id] => 1173
            [custom_price] => 11.73
        )

    [4] => Array
        (
            [id] => 1170
            [custom_price] => 22.5
        )
)

How i can sort from .. high to low & low to high .. by custom_price


Solution

  • Using usort:

    high to low

    usort($input, function ($a, $b) {return $a['custom_price'] < $b['custom_price'];});
    print_r( $input );
    

    low to high

    usort($input, function ($a, $b) {return $a['custom_price'] > $b['custom_price'];});
    print_r( $input );
    

    http://php.net/manual/en/function.usort.php

    Keep in mind this is Deprecated in 8+ must return Int values

    Using usort:

    String Comparison:

    Reference this Stackoverflow Answer

    Int Comparison

    Descending

    usort($sidebarData ->rankingData, function ($a, $b) { 
    if ($a->integerProperty == $b->intergerProperty)
    {
       return 0;
    
    } 
    return ($a->integerProperty < $b->integerProperty) ? 1 : -1;});
    

    Ascending

    usort($sidebarData ->rankingData, function ($a, $b) { 
    if ($a->integerProperty == $b->intergerProperty)
    {
       return 0;
    
    } 
    return ($a->integerProperty < $b->integerProperty) ? -1 : 1;});