0

I am working on online exams website. In this I have one associative array with key as name of subsection and values as score in respective subsection. So I want to sort that array in descending order according to values. But My values are in negative. I have used arsort function to sort associative arrays by values but it doesnt work on negative values. Actully I want to show subsections first having lowest score. I am providing my code. Please help me in this problem.

Array
(
    [sentence-equivalence] => -6
    [reading-comprehension] => -16
    [text-completion] => -20
    [algebra] => -24
    [geometry] => -26
    [arithmetic] => -31
    [common-data] => -37
    [statistics] => -38
)
JJJ
  • 32,902
  • 20
  • 89
  • 102
Yogesh k
  • 352
  • 1
  • 7
  • 22

2 Answers2

2

You could use either usort and array_reverse respectively, or if you prefer one method then you could just use uasort and pass your own comparator function. Here are the examples. Hope that helps.

$array = array(
    'sentence-equivalence' => -6,
    'reading-comprehension' => -16,
    'text-completion' => -20,
    'algebra' => -24,
    'arithmetic' => -31,
    'geometry' => -26,
    'common-data' => -37,
    'statistics' => -38,
);

asort($array, SORT_NUMERIC);
$array = array_reverse($array, true); // true stands for preserve keys.

var_dump($array);

// Otherwise you might also use uasort:

uasort($array, function($a, $b) { 
    return $a < $b;
});
Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
0

Use array_multisort and pass second parameter as SORT_DESC. Try this

$s = Array
(
    'sentence-equivalence' => -6,
    'reading-comprehension' => -16,
    'text-completion' => -20,
    'algebra' => -24,
    'arithmetic' => -31,
    'geometry' => -26,
    'common-data' => -37,
    'statistics' => -38,
);


array_multisort($s, SORT_DESC); //array_multisort($s, SORT_ASC); for ascending order
print '<pre>';
print_r($s);
MH2K9
  • 11,951
  • 7
  • 32
  • 49