Blogger Information
Blog 11
fans 0
comment 1
visits 13887
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP 数组逻辑排序方法实现,超简单:)
Alfred的学习笔记
Original
695 people have browsed it

进行排序之前:

  1. <?php
  2. /*
  3. * @Author: Alfred
  4. * @Date: 2020-01-04 13:41:54
  5. * @LastAuthor : Alfred
  6. * @LastTime : 2020-01-04 13:46:25
  7. * @Description:
  8. */
  9. $array = [
  10. ['id'=>3,'name'=>'aa'],
  11. ['id'=>7,'name'=>'bb'],
  12. ['id'=>9,'name'=>'cc'],
  13. ['id'=>2,'name'=>'dd'],
  14. ['id'=>1,'name'=>'ee'],
  15. ['id'=>8,'name'=>'ff'],
  16. ];
  17. header('Content-Type:application/json; charset=utf-8');
  18. echo json_encode($array);

得到的结果:

  1. [
  2. {
  3. "id": 3,
  4. "name": "aa"
  5. },
  6. {
  7. "id": 7,
  8. "name": "bb"
  9. },
  10. {
  11. "id": 9,
  12. "name": "cc"
  13. },
  14. {
  15. "id": 2,
  16. "name": "dd"
  17. },
  18. {
  19. "id": 1,
  20. "name": "ee"
  21. },
  22. {
  23. "id": 8,
  24. "name": "ff"
  25. }
  26. ]

使用排序功能:

  1. <?php
  2. /*
  3. * @Author: Alfred
  4. * @Date: 2020-01-04 13:41:54
  5. * @LastAuthor : Alfred
  6. * @LastTime : 2020-01-04 13:52:56
  7. * @Description:
  8. */
  9. $array = [
  10. ['id'=>3,'name'=>'aa'],
  11. ['id'=>7,'name'=>'bb'],
  12. ['id'=>9,'name'=>'cc'],
  13. ['id'=>2,'name'=>'dd'],
  14. ['id'=>1,'name'=>'ee'],
  15. ['id'=>8,'name'=>'ff'],
  16. ];
  17. //排序 ---- begin ----
  18. array_multisort(array_column($array,'id'),SORT_ASC,$array);
  19. //排序 ---- end ----
  20. header('Content-Type:application/json; charset=utf-8');
  21. echo json_encode($array);

输出结果:

  1. [
  2. {
  3. "id": 1,
  4. "name": "ee"
  5. },
  6. {
  7. "id": 2,
  8. "name": "dd"
  9. },
  10. {
  11. "id": 3,
  12. "name": "aa"
  13. },
  14. {
  15. "id": 7,
  16. "name": "bb"
  17. },
  18. {
  19. "id": 8,
  20. "name": "ff"
  21. },
  22. {
  23. "id": 9,
  24. "name": "cc"
  25. }
  26. ]

Ps:传入的数组为二维数组,key值可以任意使用,如果是使用中文姓名进行排序的话,最好先把中文转英文后,用新字段排序

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