php 数组排序
今天项目里遇到需要按照分数来排序,因该字段未入库,转化过来就是需要根据数组的某个字段的值排序
这里先介绍两个函数
1.array_column(数组,返回值得键名);
返回输入数组中某个单一列的值。
eg:
<?php
// 数组
$arr = array(
array(
'id' => 598,
'jjscore' => '6.9',
),
array(
'id' => 467,
'jjscore' => '5.0',
),
array(
'id' => 309,
'jjscore' => '7.9',
)
);
$jjscore= array_column($arr, 'jjscore');
print_r($jjscore);
?>
// 输出:
Array
(
[0] => 6.9
[1] => 5.0
[2] => 7.9
)
2.array_multisort();
array_multisort() 函数返回一个排序数组
array_multisort(排序规则数组,SORT_DESC,需要排序的数组)
SORT_DESC 表示降序
SORT_ASC - 默认 表示升序
下面开始排序
<?php
$data = array(
array(
'id' => 598,
'jjscore' => '6.9',
),
array(
'id' => 467,
'jjscore' => '5.0',
),
array(
'id' => 309,
'jjscore' => '7.9',
)
);
//根据字段jjscore对数组$data进行降序排列
$jjscore= array_column($data,'jjscore');
array_multisort($jjscore,SORT_DESC,$data);
var_dump($data);
// 输出结果 按照jjscore由高到低排序
array(3) {
[0]=>array(2) {
["id"]=>int(309)
["jjscore"]=>string(3) "7.9"
}
[1]=>array(2) {
["id"]=>int(598)
["jjscore"]=>string(3) "6.9"
}
[2]=> array(2) {
["id"]=> int(467)
["jjscore"]=> string(3) "5.0"
}
}
?>
还没有评论,来说两句吧...