zoukankan      html  css  js  c++  java
  • PHP 二维数组根据某个字段排序 复制代码 array_multisort

    //二维数组,按照里面的age从大到小降序,代码如下
    <?php
    header('Content-Type:text/html;Charset=utf-8');
    $arrUsers = array(
        array('id'   => 1,'name' => '张三','age'  => 25,),
        array('id'   => 2,'name' => '李四','age'  => 23,),
        array('id'   => 3,'name' => '王五','age'  => 40,),
        array('id'   => 4,'name' => '赵六','age'  => 31,),
        array('id'   => 5,'name' => '黄七','age'  => 20,),
    );
    
    $arrSort = array();
    foreach($arrUsers as $uniqid => $row){
        foreach($row as $key=>$value){
            $arrSort[$key][$uniqid] = $value;
        }
    }
    //$arrSort 为
    // array(
    //   "id"=>array(1,2,3,4,5),
    //   "name"=>array("张三","李四","王五","赵六","黄七"),
    //   "age"=>array(25,23,40,31,20)
    // );
    
    //array_multisort(排序字段,倒序/顺序,数组)
    array_multisort($arrSort['age'], constant('SORT_DESC'), $arrUsers);
    
    echo '<pre>';
    var_dump($arrUsers);
    
    /*
    输出结果:
    
    array(5) {
      [0]=>
      array(3) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(6) "王五"
        ["age"]=>
        int(40)
      }
      [1]=>
      array(3) {
        ["id"]=>
        int(4)
        ["name"]=>
        string(6) "赵六"
        ["age"]=>
        int(31)
      }
      [2]=>
      array(3) {
        ["id"]=>
        int(1)
        ["name"]=>
        string(6) "张三"
        ["age"]=>
        int(25)
      }
      [3]=>
      array(3) {
        ["id"]=>
        int(2)
        ["name"]=>
        string(6) "李四"
        ["age"]=>
        int(23)
      }
      [4]=>
      array(3) {
        ["id"]=>
        int(5)
        ["name"]=>
        string(6) "黄七"
        ["age"]=>
        int(20)
      }
    }
    
    */

  • 相关阅读:
    Ellipsis 的升级版 line-clamp
    Angular7里面实现 debounce search
    闭包、迭代器
    Day10 函数的进阶
    函数
    文件的操作
    Day 07基础数据补充、set、深浅拷贝
    小数据池,编码和解码
    字典
    列表、元祖的操作
  • 原文地址:https://www.cnblogs.com/idjl/p/9610585.html
Copyright © 2011-2022 走看看