进行排序之前:
<?php
/*
* @Author: Alfred
* @Date: 2020-01-04 13:41:54
* @LastAuthor : Alfred
* @LastTime : 2020-01-04 13:46:25
* @Description:
*/
$array = [
['id'=>3,'name'=>'aa'],
['id'=>7,'name'=>'bb'],
['id'=>9,'name'=>'cc'],
['id'=>2,'name'=>'dd'],
['id'=>1,'name'=>'ee'],
['id'=>8,'name'=>'ff'],
];
header('Content-Type:application/json; charset=utf-8');
echo json_encode($array);
得到的结果:
[
{
"id": 3,
"name": "aa"
},
{
"id": 7,
"name": "bb"
},
{
"id": 9,
"name": "cc"
},
{
"id": 2,
"name": "dd"
},
{
"id": 1,
"name": "ee"
},
{
"id": 8,
"name": "ff"
}
]
使用排序功能:
<?php
/*
* @Author: Alfred
* @Date: 2020-01-04 13:41:54
* @LastAuthor : Alfred
* @LastTime : 2020-01-04 13:52:56
* @Description:
*/
$array = [
['id'=>3,'name'=>'aa'],
['id'=>7,'name'=>'bb'],
['id'=>9,'name'=>'cc'],
['id'=>2,'name'=>'dd'],
['id'=>1,'name'=>'ee'],
['id'=>8,'name'=>'ff'],
];
//排序 ---- begin ----
array_multisort(array_column($array,'id'),SORT_ASC,$array);
//排序 ---- end ----
header('Content-Type:application/json; charset=utf-8');
echo json_encode($array);
输出结果:
[
{
"id": 1,
"name": "ee"
},
{
"id": 2,
"name": "dd"
},
{
"id": 3,
"name": "aa"
},
{
"id": 7,
"name": "bb"
},
{
"id": 8,
"name": "ff"
},
{
"id": 9,
"name": "cc"
}
]
Ps:传入的数组为二维数组,key值可以任意使用,如果是使用中文姓名进行排序的话,最好先把中文转英文后,用新字段排序
PHP 数组逻辑排序方法实现,超简单:)引用自己的博文 - 转战CSDN