phparrayssortingmultidimensional-array

Sort a 2D array by multiple columns


My sql table consists of ID,Book name,Genre and ratings.Currently my array from my sql table looks like this (output)

Array ( 
   [book] => Array ( 
        [0] => Array
              ( [0] => 1 
                [1] => book one 
                [2] => Fantasy/Horror 
                [4] => 8.9 )
        [1] => Array ( 
                [0] => 2 
                [1] => book two 
                [2] => Comedy 
                [4] => 8.3 ) ) )

I want to sort this array to DESC by ID.

Also in the future by title.

The array variable is $book so I wrote ksort($book) also tried arsort for some reason it doesn't work?

Is it because of the array?


Solution

  • IF you are able to: Use SQL sorting instead, because of the speed and flexibility (Use db-engine where it's appropiate) Only use array-functionality if you really need to! :-) Do something like:

    SELECT ID,Book name,Genre, ratings ORDER BY ID DESC
    

    OR

    If you have still have to use array sorting, use usort() in PHP:

    <?php
    //Book array
    $bookArray['book'][0] = array(2, 'book one', 'Fantasy/Horror', 8.9);
    $bookArray['book'][1] = array(1, 'book two ', 'Comedy', 8.3);
    
    function sortByIndex($a, $b) {
        return $a[0] - $b[0];
    }
    
    usort($bookArray['book'], 'sortByIndex');
    
    
    echo 'RESULT=' . print_r($bookArray,true);
    
    ?>
    

    Results in this output: RESULT=Array ( [book] => Array ( [0] => Array ( [0] => 1 [1] => book two [2] => Comedy [3] => 8.3 ) [1] => Array ( [0] => 2 [1] => book one [2] => Fantasy/Horror [3] => 8.9 ) ) )

    Book two comes first here, because in my example I set the first index to be 1 with value 'book two'.