薛老师在指导学员学员面试中发现有个数组相关的问题问的很多,频率很高,其中有关于数组排序的的问题。 那么我们就举个例子来看看: 数组arr为班级期末考试成绩,具体如下,要求按照语文成绩从高到低排名并输出名次 [PHP] 纯文本查看 复制代码 $arr = array(
'0' => array('name' => '朱宏宇','Chinese' =>91,'Math' => 99,'English' =>92),
'1' => array('name' => '李一凡','Chinese' =>98,'Math' => 99,'English' =>92),
'2' => array('name' => '丁飞','Chinese' =>92,'Math' => 99,'English' =>92),
'3' => array('name' => '何乐','Chinese' =>93,'Math' => 99,'English' =>92),
'98' => array('name' => '牛晓飞','Chinese' =>94,'Math' => 99,'English' =>92),
'99' => array('name' => '李聪','Chinese' =>100,'Math' => 99,'English' =>92),
);
如果对于一个一位数组根据某个字段排序很easy,那么对于二维或者是多维数组怎么处理呢???接下来我们看看对多维数组的处理方式,以上题为例,我们要根据数据$arr的语文成绩排序,那么我们首先要定义个空数据用来存放排序后的数组$tmp_array,然后定一个变量用来存放我们需要作为条件的字段$field,然后通过循环遍历将数据放到空数组里,在通过键倒序排序krsort()
[PHP] 纯文本查看 复制代码 <?php
$arr = array(
'0' => array('name' => '朱宏宇','Chinese' =>91,'Math' => 99,'English' =>92),
'1' => array('name' => '李一凡','Chinese' =>98,'Math' => 99,'English' =>92),
'2' => array('name' => '丁飞','Chinese' =>92,'Math' => 99,'English' =>92),
'3' => array('name' => '何乐','Chinese' =>93,'Math' => 99,'English' =>92),
...........
'98' => array('name' => '牛晓飞','Chinese' =>94,'Math' => 99,'English' =>92),
'99' => array('name' => '李聪','Chinese' =>100,'Math' => 99,'English' =>92),
);
$field = 'Chinese';
$tmp_array = array();
foreach($arr as $val){
$tmp_array[$val[$field]] = $val;
}
echo "<pre>";
krsort($tmp_array);
print_r($tmp_array);
?> 大家可以看到结果是如下图所示
|