1.二维数组排序方法
[PHP] 纯文本查看 复制代码 function array_sort($arr, $keys, $type = 'desc') {
$keysvalue = $new_array = array();
foreach ($arr as $k => $v) {
$keysvalue[$k] = $v[$keys];
}
if ($type == 'asc') {
asort($keysvalue);
} else {
arsort($keysvalue);
}
reset($keysvalue);
foreach ($keysvalue as $k => $v) {
$new_array[$k] = $arr[$k];
}
return $new_array;
}
需要排序的数组
[PHP] 纯文本查看 复制代码 $arr = array(
1=>array(
'id' => 5,
'name' => 'a',
'number' => 1
),
2=>array(
'id' => 4,
'name' => 'b',
'number' => 2
),
3=>array(
'id' => 12,
'name' => 'c',
'number' => 3
),
4=>array(
'id' => 21,
'name' => 'd',
'number' => 4
),
5=>array(
'id' => 30,
'name' => 'e',
'number' => 1
),
6=>array(
'id' => 35,
'name' => 'f',
'number' => 4
),
);
3.根据number进行排序
[PHP] 纯文本查看 复制代码 $arr= array_sort($arr, 'number', $type = 'desc');
4.对数组的键重新排序
[PHP] 纯文本查看 复制代码 $newArr = array();
$i = 1;
foreach ($arr as $k=>$v) {
$newArr[$i]['id'] = $v['id'];
$newArr[$i]['name'] = $v['name'];
$newArr[$i]['number'] = $v['number'];
$newArr[$i]['mingci'] = 0;
$i++;
}
unset($arr);
5.将名次写入到数组
[PHP] 纯文本查看 复制代码 foreach ($newArr as $k=>$v) {
$newArr[$k]['id'] = $v['id'];
$newArr[$k]['name'] = $v['name'];
$newArr[$k]['number'] = $v['number'];
for ($x=1; $x<=count($newArr); $x++) {
if($newArr[$x]['number'] == $newArr[$x + 1]['number']){
/*对比下一个数组*/
$newArr[$x]['mingci'] = $newArr[$x - 1]['mingci'] + 1;
}else{
if($newArr[$x]['number'] == $newArr[$x - 1]['number']){
/*对比上一个数组*/
$newArr[$x]['mingci'] = $newArr[$x - 1]['mingci'];
/*相同提示-并列第*名*/
$newArr[$x]['identical'] = $newArr[$x - 1]['mingci'];
}else{
/*获取上一个排名后+1*/
$newArr[$x]['mingci'] = $newArr[$x - 1]['mingci'] + 1;
}
}
}
}
老话如果您还是搞不定请注册本站吧10钱帮你搞定
本网站发布的修改方法为本人原创,转载请注明出处:www.sssi.cn
|