Blogger Information
Blog 57
fans 0
comment 0
visits 46963
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数组的排序规则
藍錄的博客
Original
588 people have browsed it

实例

<?php
/**
 * 数组:由键名和值二部分组成,排序也主要是依据键名与值
 * 键名: 索引和关联,升序和降序
 * 值: 也有二种排序规则
 *
 */
echo '<pre>';
//根据数组的值进行排序
//1. 升序
$arr = [45,90,22,10,3,18,33];
sort($arr); // 自然排序
//echo var_export($arr),'<hr>';

//2. 降序
$arr = [45,90,22,10,3,18,33];
rsort($arr);
//echo var_export($arr),'<hr>';

//3.回调
$arr = [45,90,22,10,3,18,33];
usort($arr, function($var1, $var2){
    $res = $var1 - $var2;
    switch ($res) {
        case ($res < 0):
//            return -1;
            return 1;  // 降序
            break;
        case ($res > 0):
//            return 1;
            return -1; // 降序
            break;
        case ($res == 0):
            return 0;
            break;
    }
});
//echo var_export($arr),'<hr>';

// usort()多维数组的排序
$stu = [
  ['name'=>'林心如','grade'=>98],
  ['name'=>'范冰冰','grade'=>55],
  ['name'=>'左小青','grade'=>73],
];
//echo '排序之前:',var_export($stu,true),'<hr>';
//用户自定义排序规则
usort($stu, function ($m, $n) {
    //$m ,$n实际上还是一个数组
   return strcmp($m['grade'], $n['grade']);
});
//echo '排序之后:',var_export($stu,true),'<hr>';

//根据数组的键进行排序
$lang = ['html'=>'标记语言','css'=>'样式表','javascript'=>'前端脚本','php'=>'后端脚本'];
ksort($lang);
echo var_export($lang),'<hr>';

$lang = ['html'=>'标记语言','css'=>'样式表','javascript'=>'前端脚本','php'=>'后端脚本'];
krsort($lang);
echo var_export($lang),'<hr>';

//使用自定义的回调函数,对键名进行排序
// 根据键名的第二个字母进行排序
$lang = ['html'=>'标记语言','css'=>'样式表','javascript'=>'前端脚本','php'=>'后端脚本'];
uksort($lang, function($m, $n) {
    $a = substr($m,1,1 );
    $b = substr($n,1,1 );
    return strcmp($a, $b);
});
echo var_export($lang),'<hr>';

运行实例 »

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

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