• PHP开发笔记:二维数组根据某一项来进行排序


    比如说我们现在有一个二维数组:

    $arr = array( 
    ‘d' => array(‘id' => 5, ‘name' => 1, ‘age' => 7), 
    ‘b' => array(‘id' => 2,'name' => 3,'age' => 4), 
    ‘a' => array(‘id' => 8,'name' => 10,'age' => 5), 
    ‘c' => array(‘id' => 1,'name' => 2,'age' => 2) 
    ); 

    目标是针对于这个二维数组的每一项,根据他们的age来进行排序,排序过程中我们会使用到PHP内置的array_multisort() 函数:

    function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){ 
        if(is_array($multi_array)){ 
            foreach ($multi_array as $row_array){ 
                if(is_array($row_array)){ 
                    $key_array[] = $row_array[$sort_key]; 
                }else{ 
                    return false; 
                } 
            } 
        }else{ 
            return false; 
        } 
        array_multisort($key_array,$sort,$multi_array); 
        return $multi_array; 
    } 

    我们来看一下实例的处理结果:

    echo “<pre/>”; 
    print_r(multi_array_sort($arr,'age'));exit; 
    //输出 
    Array 
    ( 
    [c] => Array 
    ( 
    [id] => 1 
    [name] => 2 
    [age] => 2 
    ) 
    [b] => Array 
    ( 
    [id] => 2 
    [name] => 3 
    [age] => 4 
    ) 
    [a] => Array 
    ( 
    [id] => 8 
    [name] => 10 
    [age] => 5 
    ) 
    [d] => Array 
    ( 
    [id] => 5 
    [name] => 1 
    [age] => 7 
    ) 
    ) 
  • 相关阅读:
    Android ViewPager实现选项卡切换
    Android Fragment是什么
    Android 点击文字实现跳转
    海底捞的十五天,让我重当程序员
    saltstack 实现haproxy+keepalived
    saltstack 实现系统初始化
    saltstack 实现redis主从
    python类基础
    Mysql 数据库备份工具 xtrabackup
    Python函数式编程
  • 原文地址:https://www.cnblogs.com/starkiller/p/5731797.html
Copyright © 2020-2023  润新知