指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

在实际开发过程中,可能会对数组或者对象根据指定的属性排序,那么通过php的usort排序是非常好用的

<?php

/**
 * 测试类
 *
 * Created by PhpStorm.
 * User: guoshipeng
 * Date: 2022/10/20
 * Time: 10:43
 */
namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;

class TestController extends Controller
{

    /**
     * 测试,通过usort配合组合比较进行排序
     */
    public function index()
    {
        //这里简单的用一个普通数组排序,也可以对一个对象中的属性,比如说年龄排序,直接就是 $a->age <=> $b->age
        //官方文档有很好的说明了: https://www.php.net/manual/en/function.usort.php
        $a = array(3, 2, 5, 6, 1, 1);
        usort($a, [self::class, 'cmp']);
        dd($a);//[1,2,3,4,5,6]
    }

    /**
     * 组合比较 <=>
     *
     * @param $a
     * @param $b
     * @return int
     */
    private static function cmp($a, $b){

        // 太空符,直接比较
        //return $a <=> $b;

        // 原生三目运算
        //return $a > $b ? 1 : ( $a==$b ? 0 : -1 );

        //return an integer that is either "less than, equal to, or greater than zero". There is no requirement to restrict the value returned to -1, 0, 1.
        //不一定要返回 1 0 -1,只要是有区分度的三个值都可以
        return $a - $b;
    }

}