Blogger Information
Blog 48
fans 0
comment 0
visits 36812
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数组排序-2018.08.27
雨天的博客
Original
654 people have browsed it

实例

<?php
/**
 * 数组是有键和值两部分组成,排序也主要依据键名与值;
 * 键名:索引和关联,升序和降序
 * 值:也有2中排序规则
 */
//1.根据数组的值进行排序
$arr = [20,50,10,23,56,45,80];
//升序
sort($arr);//排序结果会影响原始数组
echo var_export($arr);
echo '<br>';

$arr = [20,50,10,23,56,45,80];
//降序
rsort($arr);
echo var_export($arr);
echo '<br>';

$arr = [20,50,10,23,56,45,80];
//回调
usort($arr,function($val1,$val2){
    $res = $val1-$val2;
    switch ($res)
    {
        case ($res<0):
            return -1;break;
        case ($res>0):
            return 1;break;
        default:
            return 0;
    }
});
echo var_export($arr);
echo '<br>';

//usort()多维数组排序
$stu = [
    ['name'=>'黄蓉','grade'=>90],
    ['name'=>'郭靖','grade'=>80],
    ['name'=>'杨康','grade'=>60],
    ['name'=>'洪七公','grade'=>99]
];
//用户自定义排序
usort($stu,function ($m,$n){
    return strcmp($m['grade'],$n['grade']);
});
echo var_export($stu);
echo '<br>';

//用户数组的键进行排序
$lang = ['html'=>'标记语言','php'=>'预处理语言','css'=>'样式表','js'=>'脚本语言'];
ksort($lang);
echo var_export($lang);
echo '<br>';

//键名降序
$lang = ['html'=>'标记语言','php'=>'预处理语言','css'=>'样式表','js'=>'脚本语言'];
krsort($lang);
echo var_export($lang);
echo '<br>';

//使用自定的回调函数,对键名进行排序uksort()
$lang = ['html'=>'标记语言','php'=>'预处理语言','css'=>'样式表','js'=>'脚本语言'];
uksort($lang,function ($m,$n){
    $a = substr($m,1,1);
    $b = substr($n,1,1);
    return strcmp($a,$b);
});
echo var_export($lang);

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post