shell
shell

Reputation: 401

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?

Upvotes: 0

Views: 96

Answers (3)

bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

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'.

Upvotes: 1

Neeraj
Neeraj

Reputation: 244

Just you need to change your Select Statement. It should be something like this -

select id,bookname,genre,ratings from yourtable ORDER BY id DESC,bookname;

Upvotes: 0

chrislondon
chrislondon

Reputation: 12031

The easiest way is to add this to your SQL statement at the end:

ORDER BY id DESC

Also if you really want to know how to do it in PHP you would do it this way:

function cmp($a, $b)
{
    if ($a[0] == $b[0]) {
        return 0;
    }
    return ($a[0] > $b[0]) ? -1 : 1;
}

usort($array['book'], "cmp");

Upvotes: 1

Related Questions