Laravel 地区列表 - 拼音排序

Laravel 地区列表 - 拼音排序

对于城市数据可以参考:Laravel 多级联动

1
2
# 安装依赖
$ composer require "overtrue/pinyin:~4.0"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php

namespace App\Http\Controllers;

use Overtrue\Pinyin\Pinyin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class AreaController extends Controller
{
/**
* 地区列表 - 拼音排序
*
* @return \Illuminate\Http\Response
*/
public function list()
{
$list_tmp = DB::table('area')
->select('code', 'name')
->orderBy(DB::raw('convert(name using gbk)'))
->get();

$pinyin = new Pinyin();

$list = [];

$list_tmp->map(function($item) use(&$list, $pinyin) {
// 去除城市名最后面的市字
// if(substr($item->name, -3) === '市') {
// $item->name = substr($item->name, 0, -3);
// }

// 获取城市名第一个字
$name_first = substr($item->name, 0, 3);

// 获取拼音
$name_pinyin = $pinyin->convert($name_first)[0];

// 获取第一个字母并且转换为大写
$name_pinyin = strtoupper(substr($name_pinyin, 0, 1));

if(!isset($list[$name_pinyin])) {
$list[$name_pinyin] = [];
}

$list[$name_pinyin][] = (array) $item;
});

return response()
->json([
'code' => 1,
'data' => $list,
]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"code": 1,
"data": {
"G": [
{
"code": 5108,
"name": "广元市"
},
{
"code": 4401,
"name": "广州市"
}
],
"S": [
{
"code": 4403,
"name": "深圳市"
}
]
}
}
往上