<=>
这个运算符可以用于比较两个表达式,并返回 -1、0 或 1,具体取决于它们的相对值:
- 返回
-1
,如果左边的值小于右边的值; - 返回
0
,如果两边的值相等; - 返回
1
,如果左边的值大于右边的值。
这个运算符非常适合用于排序操作或任何需要根据比较结果来确定顺序的情况。以下是一些使用例子:
echo 1 <=> 1; // 输出 0
echo 1 <=> 2; // 输出 -1
echo 2 <=> 1; // 输出 1
// 在数组排序中使用
usort($array, function($a, $b) {
return $a['price'] <=> $b['price'];
});
$array = [
['name' => '张三', 'price' => 100],
['name' => '李四', 'price' => 200],
['name' => '王五1', 'price' => 150],
['name' => '王五2', 'price' => 110],
['name' => '赵六1', 'price' => 250],
['name' => '赵六2', 'price' => 250],
['name' => '赵六3', 'price' => 250],
];
usort($array, function($a, $b) {
return $a['price'] <=> $b['price'];
});
dump($array);
结果
array(7) {
[0] => array(2) {
["name"] => string(6) "张三"
["price"] => int(100)
}
[1] => array(2) {
["name"] => string(7) "王五2"
["price"] => int(110)
}
[2] => array(2) {
["name"] => string(7) "王五1"
["price"] => int(150)
}
[3] => array(2) {
["name"] => string(6) "李四"
["price"] => int(200)
}
[4] => array(2) {
["name"] => string(7) "赵六1"
["price"] => int(250)
}
[5] => array(2) {
["name"] => string(7) "赵六2"
["price"] => int(250)
}
[6] => array(2) {
["name"] => string(7) "赵六3"
["price"] => int(250)
}
}