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'],
    // ]
  • 相关阅读:
    pandas
    使用Selenium模拟浏览器抓取淘宝商品美食信息
    Pycharm安装第三方库
    shift 函数
    mysql 基础(一)
    mysql基础(三)
    Python Programming for Finance
    进程线程
    股票上市代码及上市时间
    SQLyog连接数据库报错plugin caching_sha2_password could not be loaded
  • 原文地址:https://www.cnblogs.com/cxx8181602/p/14836511.html
Copyright © 2011-2022 走看看