CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2008
    Location
    United States
    Posts
    71

    PHP - Sorting Multidimensional Arrays

    This has been driving me NUTS for two days now. How to efficiently sort a multidimensional array by any column.

    For example, say I have this multidimensional array (arrays withing an array):
    Code:
    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 20
                [2] => hello
            )
    
        [1] => Array
            (
                [0] => 2
                [1] => 1
                [2] => hi
            )
    
        [2] => Array
            (
                [0] => 3
                [1] => 100
                [2] => good evening
            )
    
        [3] => Array
            (
                [0] => 4
                [1] => 5
                [2] => good morning
            )
    )
    This data would actually be stored in a mysql database, and this is the format the array is in when I pull the data.

    The first value in each array is the index, the second value is what I want to sort the array's by, and the third is just some textual information.

    How would I sort the array so that it would become:
    Code:
    Array
    (
        [0] => Array
            (
                [0] => 2
                [1] => 1
                [2] => hi
            )
    
        [1] => Array
            (
                [0] => 4
                [1] => 5
                [2] => good morning
            )
    
        [2] => Array
            (
                [0] => 1
                [1] => 20
                [2] => hello
            )
    
        [3] => Array
            (
                [0] => 3
                [1] => 100
                [2] => good evening
            )
    )
    Thanks for helping! I really haven't learned about sorting algorithms and appreciate it!

  2. #2
    Join Date
    May 2002
    Posts
    10,943

    Re: PHP - Sorting Multidimensional Arrays

    If the data is generated by a database then always sort the data from the database to output into an array. A small example...

    Code:
    SELECT * FROM table ORDER BY column ASC
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured