这个usort函数返回的数组与我想要的相反。它返回一个类似("1"、"2"、"3")的数组。如何使其返回("3"、"2"、"1")?
usort($myArray, function($a, $b) {
return $a["comments"] - $b["comments"];
});
只需反转参数?
usort($myArray, function($a, $b) {
return $b["comments"] - $a["comments"];
});
从PHP7.4开始,你可以这样写:
usort($myArray, fn($a, $b) => $b["comments"] - $a["comments"]);
usort($myArray, function($a, $b) {
return $b["comments"] - $a["comments"];
});
只需将A更改为B,将B更改为A即可。
您可以反转函数输出。
usort($myArray, function($a, $b) {
return $b["comments"] - $a["comments"];
});
usort($myArray, function($a, $b) {
if($a['comments'] === $b['comments']) {
return 0;
}
return ($a['comments'] > $b['comments']) ? -1 : 1;
});
$myArray = array("1", "2", "3");
$reversed_array = array_reverse($myArray);