sort associative arrays

Discussion in 'PHP' started by bumbar, Sep 13, 2009.

  1. #1
    Hallo!

    I have an associative array containing dates.

    here the code:

    
    $arr = array ("2009-03-11", "2009-06-22", "2007-04-14", "2009-04-14", "2009-04-15");
    
    sort ($arr);
    
    echo "<pre>";
    print_r ($arr);
    echo "</pre>";
    
    PHP:

    It displays
    
    Array
    (
        [0] => 2007-04-14
        [1] => 2009-03-11
        [2] => 2009-04-14
        [3] => 2009-04-15
        [4] => 2009-06-22
    )
    
    
    	
    how to print the result in reverse chronologyБ
    
    2009-06-22
    2009-04-15
    2009-04-14
    2009-03-11
    2007-04-14
    
    
    HTML:
    Please help me :(

    Thanx!
     
    bumbar, Sep 13, 2009 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    Are you getting this list from a MySQL database, you can get them sorted there.

    You can also use arsort instead of sort.
     
    Last edited: Sep 13, 2009
    ThePHPMaster, Sep 13, 2009 IP
  3. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #3
    premiumscripts, Sep 13, 2009 IP
  4. ven

    ven Member

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #4
    You could use
    
    $arr = array_reverse(sort($arr));
    
    PHP:
     
    ven, Sep 14, 2009 IP
  5. premiumscripts

    premiumscripts Peon

    Messages:
    1,062
    Likes Received:
    48
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Um dude there's already a specific function for this as I said in the previous post, "arsort". There's no need to combine other functions to recreate the same behavior.
     
    premiumscripts, Sep 14, 2009 IP
  6. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #6
    Well the example isn't an associative array, and it's also using a format for the dates that puts the most significant portion of the date first with a zero-fill in the lessor parts (YYYY-MM-DD), so "sort" or since you want reverse order, "rsort" will work.
     
    joebert, Sep 15, 2009 IP