I need to sum columns and sort them highest to lowest.
This is what I've tried!
$sth = $db->prepare("SELECT sum(A), sum(S), sum(D), sum(F) FROM XXX order by A, S, D, F DESC");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
This is what the output looks like:
Array ( [sum(A)] => 38 [sum(S)] => 194 [sum(D)] => 40 [sum(F)] => 164 )
Why not just use rsort()
, in php when the results are returned??
sort()
will to lowest to highest, rsort()
will do highest to lowest
rsort($result);
print_r($result);
Or to keep the associative features of your array, use asort()
(low->high), or arsort()
; (high->low)
arsort($result);
print_r($result);
SELECT sum(A), sum(S), sum(D), sum(F) FROM XXX order by S DESC, A DESC, D DESC, F DESC
Basically you have to add the DESC
to each column you want sorted in descending order. The default being ASCending order.
Copy and paste this code and you can figure it out:
$sth = array(
'sumA' => 38,
'sumB' => 194,
'sumC' => 40,
'sumD' => 164
);
arsort($sth);
foreach($sth as $element => $num){
echo $element . $num . '</br>';
}