zoukankan      html  css  js  c++  java
  • php二维数组根据某两字段比较大小,重新自定义排序

     php数组函数array_push()、array_pop()、array_shift() 、array_unshift()简单用法示例:

    <?php
    /**
     * array_push()将一个或多个单元压入数组的末尾(入栈)
     */
    $stack = ['a', 'b'];
    array_push($stack, 'cc', 'dd', ['eee','fff']);
    var_dump($stack);
    //输出结果:['a','b','cc','dd',['eee','fff']]
    
    /**
     * array_pop() 将数组最后一个单元弹出(出栈)
     */
    $stack = ['a', 'b', 'c'];
    array_pop($stack);
    var_dump($stack);
    //输出结果:['a','b']
    
    /**
     * array_shift()将数组开头的单元移出数组
     */
    $stack = ['a', 'b','c'];
    array_shift($stack);
    var_dump($stack);
    //输出结果:['b', 'c'];
    
    /**
     * array_unshift()在数组开头插入一个或多个单元 
     */
    $stack = ['a', 'b'];
    array_unshift($stack, 'cc', 'dd', ['eee','fff']);
    var_dump($stack);
    //输出结果:['cc','dd',['eee','fff'],'a','b']

    demo示例:  mysql查询二维多条数据(二维数组),需要根据某两字段比较大小,重新再排序

    <?php
    
    $mysqlDatas = [
        ['id' => 1, 'goods' => 'milk','totalPrice' => '9','balance' => '10'],
        ['id' => 2, 'goods' => 'apple','totalPrice' => '15','balance' => '10'],
        ['id' => 3, 'goods' => 'banana','totalPrice' => '5','balance' => '10'],
        ['id' => 4, 'goods' => 'orange','totalPrice' => '19','balance' => '10'],
    ];
    
    
    $datas = [];
    foreach ($mysqlDatas as $data){
        //总价大于余额数据排序最前面
        if($data['totalPrice'] > $data['balance']){
            array_unshift($datas, $data);
        }else{
            array_push($datas, $data);
        }
    }
    var_dump($datas);
    
    //输出结果:
    // [
    //     ['id' => 4, 'goods' => 'orange','totalPrice' => '19','balance' => '10'],
    //     ['id' => 2, 'goods' => 'apple','totalPrice' => '15','balance' => '10'],
    //     ['id' => 1, 'goods' => 'milk','totalPrice' => '9','balance' => '10'],
    //     ['id' => 3, 'goods' => 'banana','totalPrice' => '5','balance' => '10'],
    // ]
  • 相关阅读:
    阿里妈妈MaxCompute架构演进_-_AON(MPI)集群
    阿里云ECS部署Grafana接入zabbix
    ECS实例RAM角色实践
    上海云栖—人工智能-视觉计算专场预热
    阿里云论坛版主制作最新教程汇总贴
    移动相关的css
    GULP入门(一)
    mongodb+nodejs 增删查的demo
    nodejs+express 初学(三)
    nodejs+express 初学(二)
  • 原文地址:https://www.cnblogs.com/cxx8181602/p/14836511.html
Copyright © 2011-2022 走看看