Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to sort an given array by it's any key index

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 172
    Comment on it

    Hello Reader's! if you have an given array on with you want to sort with any selected key index as show below:-

    1. Array
    2. (
    3. [0] => Array
    4. (
    5. [configuration_id] => 10
    6. [id] => 1
    7. [optionNumber] => 3
    8. [optionActive] => 1
    9. [lastUpdated] => 2010-03-17 15:44:12
    10. )
    11.  
    12. [1] => Array
    13. (
    14. [configuration_id] => 9
    15. [id] => 1
    16. [optionNumber] => 2
    17. [optionActive] => 1
    18. [lastUpdated] => 2010-03-17 15:44:12
    19. )
    20.  
    21. [2] => Array
    22. (
    23. [configuration_id] => 8
    24. [id] => 1
    25. [optionNumber] => 1
    26. [optionActive] => 1
    27. [lastUpdated] => 2010-03-17 15:44:12
    28. )
    29. )

    And you want your array to be like this:-

    1. Array
    2. (
    3. [0] => Array
    4. (
    5. [configuration_id] => 8
    6. [id] => 1
    7. [optionNumber] => 1
    8. [optionActive] => 1
    9. [lastUpdated] => 2010-03-17 15:44:12
    10. )
    11.  
    12. [1] => Array
    13. (
    14. [configuration_id] => 9
    15. [id] => 1
    16. [optionNumber] => 2
    17. [optionActive] => 1
    18. [lastUpdated] => 2010-03-17 15:44:12
    19. )
    20.  
    21. [2] => Array
    22. (
    23. [configuration_id] => 10
    24. [id] => 1
    25. [optionNumber] => 3
    26. [optionActive] => 1
    27. [lastUpdated] => 2010-03-17 15:44:12
    28. )
    29. )

    Now you have to use the code as written below:-

    1. function cmp_by_optionNumber($a, $b) {
    2. return $a["optionNumber"] - $b["optionNumber"];
    3. }
    4.  
    5. usort($array, "cmp_by_optionNumber");

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: