php 数组排序

缺乏、安全感 2021-12-14 13:51 347阅读 0赞

今天项目里遇到需要按照分数来排序,因该字段未入库,转化过来就是需要根据数组的某个字段的值排序
这里先介绍两个函数
1.array_column(数组,返回值得键名);
返回输入数组中某个单一列的值。
eg:

  1. <?php
  2. // 数组
  3. $arr = array(
  4. array(
  5. 'id' => 598,
  6. 'jjscore' => '6.9',
  7. ),
  8. array(
  9. 'id' => 467,
  10. 'jjscore' => '5.0',
  11. ),
  12. array(
  13. 'id' => 309,
  14. 'jjscore' => '7.9',
  15. )
  16. );
  17. $jjscore= array_column($arr, 'jjscore');
  18. print_r($jjscore);
  19. ?>
  20. // 输出:
  21. Array
  22. (
  23. [0] => 6.9
  24. [1] => 5.0
  25. [2] => 7.9
  26. )

2.array_multisort();
array_multisort() 函数返回一个排序数组
array_multisort(排序规则数组,SORT_DESC,需要排序的数组)
SORT_DESC 表示降序
SORT_ASC - 默认 表示升序
下面开始排序

  1. <?php
  2. $data = array(
  3. array(
  4. 'id' => 598,
  5. 'jjscore' => '6.9',
  6. ),
  7. array(
  8. 'id' => 467,
  9. 'jjscore' => '5.0',
  10. ),
  11. array(
  12. 'id' => 309,
  13. 'jjscore' => '7.9',
  14. )
  15. );
  16. //根据字段jjscore对数组$data进行降序排列
  17. $jjscore= array_column($data,'jjscore');
  18. array_multisort($jjscore,SORT_DESC,$data);
  19. var_dump($data);
  20. // 输出结果 按照jjscore由高到低排序
  21. array(3) {
  22. [0]=>array(2) {
  23. ["id"]=>int(309)
  24. ["jjscore"]=>string(3) "7.9"
  25. }
  26. [1]=>array(2) {
  27. ["id"]=>int(598)
  28. ["jjscore"]=>string(3) "6.9"
  29. }
  30. [2]=> array(2) {
  31. ["id"]=> int(467)
  32. ["jjscore"]=> string(3) "5.0"
  33. }
  34. }
  35. ?>

发表评论

表情:
评论列表 (有 0 条评论,347人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PHP数组排序详解

    PHP提供了很多种不同方式对数组进行排序的函数,这些函数允许用户在数组内部对元素进行排列。通过排序可以对数据进行合理的管理,提高程序的执行效率。 数字数组排序 1

    相关 php 数组排序

    今天项目里遇到需要按照分数来排序,因该字段未入库,转化过来就是需要根据数组的某个字段的值排序 这里先介绍两个函数 1.array\_column(数组,返回值得键名);