Sorting an array

Discussion in 'PHP' started by yoda699, May 29, 2012.

  1. #1
    Hi all,

    I'm trying to sort an array and I'm having a problem with it.
    Here's an example of an array:

    Array ( [0] =>
    1a1 [1] => 3b2 [2] => 2c3 [3] => 8d4 [4] => 4e5 [5] => 9f6 [6] => 5g7 [7] => 14h8 [8] => 6i9 [9] => 12j10 [10] => 10k11 [11] => 7l12 [12] => 11m13 [13] => 13n14 [14] => 15o15 )

    I would like it to be sorted out by the first number only (the ones that I marked in red). Thus, the new array should look like:

    Array ( [0] => 1a1 [1] => 2c3 [2] =>3b2 [3] => 4e5 [4] => 5g7 [5] => 6i9 [6] =>7l12 [7] => 8d4 [8] => 9f6 [9] =>10k11 [10] => 11m13 [11] => 12j10 [12] => 13n14 [13] => 14h8 [14] => 15o15 )

    I'm using the following code:
    
    asort($array);
    print_r($array);
    
    PHP:

    However, what I am getting is:

    Array ( [10] => 10k11 [12] => 11m13 [9] => 12j10 [13] => 13n14 [7] => 14h8 [14] => 15o15 [0] => 1a1 [2] => 2c3 [1] => 3b2 [4] => 4e5 [6] => 5g7 [8] => 6i9 [11] => 7l12 [3] => 8d4 [5] => 9f6 )

    Any ideas what is going wrong. Why does key #10 jumps to the front of the array?
    Thanks,
     
    yoda699, May 29, 2012 IP
  2. ROOFIS

    ROOFIS Well-Known Member

    Messages:
    1,234
    Likes Received:
    30
    Best Answers:
    5
    Trophy Points:
    120
    #2
    There's about 12 flavors of 'sort' in php though the first one I thought of for your scenario was natsort or sort naturally. It's best to utilize natcasesort though as this method is case insensitive.

    example:

    
    <?php
    echo '<pre>';
    
    $array = Array(0 => '1a1', 1 => '3b2', 2 => '2c3', 3 => '8d4', 4 => '4e5', 5 => '9f6', 6 => '5g7', 7 => '14h8', 8 => '6i9', 9 => '12j10', 10 => '10k11', 11 => '7l12', 12 => '11m13', 13 => '13n14', 14 => '15o15');
    natcasesort($array);
    $output = array_values($array);  //note* natcasesort preserves keys too, use array_values to hierarchy key entries!
    print_r($output);
    
    echo '</pre>';
    ?>
    
    PHP:




    ROOFIS :cool:
     
    ROOFIS, May 30, 2012 IP
  3. yoda699

    yoda699 Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Cool. thanks for the info!
     
    yoda699, May 30, 2012 IP