简体   繁体   English

如何排序在php中具有负值的关联数组?

[英]how to sort associative array having negative values descending in php?

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. 我已使用arsort函数按值对关联数组进行排序,但对负值不起作用。 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
)

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. 您可以分别使用usortarray_reverse ,或者如果您更喜欢一种方法,则可以只使用uasort并传递自己的比较器函数。 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;
});

Use array_multisort and pass second parameter as SORT_DESC . 使用array_multisort并将第二个参数作为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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM