Quote:
Originally Posted by vegetable21
Surely the above is sorting each $row array within $arr rather than sorting by $arr['Turnover'] within the whole $arr?
I never used arrays in php before, but it seems to be not logical to me how you try to sort it . All sort functions I have seen so far, no matter what language, need an index and the array itself. But $arr['Turnover'] only gives you the index, so where is the array itself in your argument list that you pass to your sort function ???
I googled an found this:
Quote:
static function multi2dSortAsc(&$arr, $key){
$sort_col = array();
foreach ($arr as $sub) $sort_col[] = $sub[$key];
array_multisort($sort_col, $arr);
}
The crux is that we have to create the 1D array we want to sort by on the fly, once we have this array it can be used to sort the parent 2D array by passing it as a second argument.
As I said, I am a newbie in php, but how I understand it is that you did not pass the array as second argument. Just add it in your original code:
- array_multisort($arr['Turnover'], $arr, SORT_NUMERIC, SORT_DESC);
I have no possibility to run PHP code myself, so if that doesn't work, then you should ask this question about sorting in the PHP forum again.
If you need the array sorted by different columns (I assume you have a column name in your GUI or webpage that you can click or select to sort it), then get it unsorted from database, buffer it and sort it in php. In this case you only access the database once and get the data, no matter how often the user wants it to sort. That's a huge performance gain than doing the opposite: get it again and again from database everytime the user clicks on a column to sort it.
And what about different character sets and collations your DB uses while sorting? How does your database suport that? I guess with proprietary SQL-syntax only. And if you change the database? Then you need to rewrite all your SQLs! In opposite to that the php-code for sorting an array always stays the same.
Sorting by php puts load on the webserver, sorting by DB puts load on the database server. What if you run into performance problems? Then in most cases it's much easier to just add a new webserver than to add a new database server and do all the required data synchronizations between both DB-servers.
Anyway, there is only one situation where you should let the database sort the results:
If for example the query returns million of records, but you only need the first 10 of them (SQL-command "limit"). Then it's a lot of faster that way. But in your query provided you don't use.
if you still want to let the database sort it then you could just modify the "ORDER BY Turnover DESC" clause in your SQL-query by replacing "Turnover" with the column name you want to sort by.