SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Apr 2007
    Posts
    117
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Array sorting by value

    I have the following array;

    Array
    (
    [0] => Array
    (
    [value] => 10
    [base] => 2.99
    [renewal] => 1.99
    )

    [1] => Array
    (
    [value] => 50
    [base] => 3.99
    [renewal] => 2.99
    )

    [2] => Array
    (
    [value] => 100
    [base] => 4.99
    [renewal] => 3.99
    )

    )

    But need to sort according to the value entry "highest first". I'm currently using array_reverse but the input order is not necessarily going to be lowest to highest so I need a more reliable method.

    Could somebody please point me in the right direction?

    Thanks in advance.

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,196
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Have a read about the array_multisort() function which may be what you want to use.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2008
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb

    This might help you:

    PHP Code:
    $array[0] = array('value' => 10'base' => 2.99'renewal' => 1.99);
    $array[1] = array('value' => 50'base' => 3.99'renewal' => 2.99);
    $array[2] = array('value' => 100'base' => 4.99'renewal' => 3.99);

    function 
    cmp($a$b){
        if (
    $a == $b)
            return 
    0;
        
        return 
    $a['value'] < $b['value'];
    }

    usort($array'cmp');

    echo 
    '<pre>';
    print_r($array);
    echo 
    '</pre>'
    Result is:

    Array
    (
    [0] => Array
    (
    [value] => 100
    [base] => 4.99
    [renewal] => 3.99
    )

    [1] => Array
    (
    [value] => 50
    [base] => 3.99
    [renewal] => 2.99
    )

    [2] => Array
    (
    [value] => 10
    [base] => 2.99
    [renewal] => 1.99
    )
    )

  4. #4
    SitePoint Zealot
    Join Date
    Apr 2007
    Posts
    117
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks folks. array_multisort was exactly what I was looking for.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •