zoukankan      html  css  js  c++  java
  • array_multisort 对关联数组进行排序的问题 PHP

    我们在php的数组操作中经常用到对数组进行排序的问题,这里说的是对关联数组进行排序
    需要用到函数 array_multisort 。
    array_multisort(array_column($arr, 'weight'),SORT_NUMERIC, SORT_ASC, $arr);   // 对关联数组 $arr  将键列'weight'转换为数字进行升序排序
    SORT_NUMERIC  // 转换为数字排序
    SORT_STRING  // 转换为文本排序
    SORT_ASC     // 升序
    SORT_DESC    // 降序

    示例:
    原关联数组:
    $data[] = array('volume' => 'id100343', 'weight' => '4');
    $data[] = array('volume' => 'id100212', 'weight' => '1');
    $data[] = array('volume' => 'id104104', 'weight' => '10');
    var_dump($data);

    按照weight进行排序(数字方式SORT_NUMERIC):
    array_multisort(array_column($data, 'weight'),SORT_NUMERIC, SORT_ASC, $data); 

    输出结果:
    array(3) {
      [0]=>
      array(2) {
        ["volume"]=>
        string(8) "id100212"
        ["weight"]=>
        string(1) "1"
      }
      [1]=>
      array(2) {
        ["volume"]=>
        string(8) "id100343"
        ["weight"]=>
        string(1) "4"
      }
      [2]=>
      array(2) {
        ["volume"]=>
        string(8) "id104104"
        ["weight"]=>
        string(2) "10"
      }
    }
    按照weight进行排序(文本方式SORT_STRING):
    array_multisort(array_column($data, 'weight'),SORT_STRING, SORT_ASC, $data); 
    array(3) {
      [0]=>
      array(2) {
        ["volume"]=>
        string(8) "id100212"
        ["weight"]=>
        string(1) "1"
      }
      [1]=>
      array(2) {
        ["volume"]=>
        string(8) "id104104"
        ["weight"]=>
        string(2) "10"
      }
      [2]=>
      array(2) {
        ["volume"]=>
        string(8) "id100343"
        ["weight"]=>
        string(1) "4"
      }
    }

    需要注意10作为数字和文本的区别。
  • 相关阅读:
    【转】异常处理模块
    【转】整套完整安全的API接口解决方案
    百度地图API功能集锦
    VS2015 使用Razor编写MVC视图时,Razor智能提示消失,报各种红线解决方案。
    算法初涉-解决比9*9数独更复杂的结构
    SQL时间相关
    ubuntu 安装
    dwa 设置多个目标点,倒车设计
    ros 信号周期的简单实现
    C++学习记录 第一章:初始
  • 原文地址:https://www.cnblogs.com/mywebnumber/p/5552596.html
Copyright © 2011-2022 走看看