usort以相反的顺序返回数组

时间:2013-09-01 10:58:32

标签: php

这个usort函数正在从我想要的方向返回数组。它返回一个数组(“1”,“2”,“3”)。如何让它返回(“3”,“2”,“1”)?

usort($myArray, function($a, $b) {
    return $a["comments"] - $b["comments"];
});

6 个答案:

答案 0 :(得分:23)

只需反转参数?

usort($myArray, function($a, $b) {
    return $b["comments"] - $a["comments"];
});

答案 1 :(得分:2)

你可以改变你的功能输出。

usort($myArray, function($a, $b) {
    return $b["comments"] - $a["comments"];
});

答案 2 :(得分:2)

usort($myArray, function($a, $b) {
    return $b["comments"] - $a["comments"];
});

只需将A更改为B,将B更改为A.

答案 3 :(得分:0)

$myArray  = array("1", "2", "3");
$reversed_array = array_reverse($myArray);

答案 4 :(得分:0)

usort($myArray, function($a, $b) {
    if($a['comments'] === $b['comments']) {
        return 0;
    }

    return ($a['comments'] > $b['comments']) ? -1 : 1;
});

答案 5 :(得分:-2)

如果这些都不起作用,您总是可以两次发布命令,它将颠倒顺序。

usort($myArray, function($a, $b) {
    return $a["comments"] - $b["comments"];
});
usort($myArray, function($a, $b) {
    return $a["comments"] - $b["comments"];
});
相关问题