123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- <?php
- namespace Pinyin\Lib;
- use Dever;
- Dever::apply('const', 'pinyin', 'overtrue/src');
- Dever::apply('DictLoaderInterface', 'pinyin', 'overtrue/src');
- Dever::apply('FileDictLoader', 'pinyin', 'overtrue/src');
- Dever::apply('GeneratorFileDictLoader', 'pinyin', 'overtrue/src');
- Dever::apply('MemoryFileDictLoader', 'pinyin', 'overtrue/src');
- Dever::apply('Pinyin', 'pinyin', 'overtrue/src');
- use Overtrue\Pinyin\Pinyin as Core;
- class Convert
- {
-
- protected $pinyin = null;
- public function __construct()
- {
- if (!$this->pinyin) {
- $this->pinyin = new Core('Overtrue\Pinyin\MemoryFileDictLoader');
- }
- }
-
- public function getPinyinFunc()
- {
- return $this->pinyin;
- }
-
- public function getPinyin($string, $link = '')
- {
- return $this->pinyin->permalink($string, $link);
- }
-
- public function getPinyinName($string)
- {
- return $this->pinyin->name($string);
- }
-
- public function getPinyinContent($string, $state = false)
- {
- return $this->pinyin->sentence($string, $state);
- }
-
- public function groupByPinyinFirst(array $data, $targetKey = 'name')
- {
- if (!$this->pinyin) {
- $this->pinyin = new Core('Overtrue\Pinyin\MemoryFileDictLoader');
- }
- $data = array_map(function ($item) use ($targetKey) {
- return array_merge($item, [
- 'first' => $this->getPinyinFirst($item[$targetKey]),
- ]);
- }, $data);
- $data = $this->sortPinyinFirst($data);
- return $data;
- }
-
- public function sortPinyinFirst(array $data, $first = 'first')
- {
- $sortData = [];
- foreach ($data as $key => $value) {
- $sortData[$value[$first]][] = $value;
- }
- ksort($sortData);
- if (isset($sortData[''])) {
- $tmp = $sortData[''];
- unset($sortData['']);
- $sortData[''] = $tmp;
- }
- return $sortData;
- }
-
- public function getPinyinFirst($str)
- {
- if (empty($str)) {
- return '';
- }
- if (!$this->pinyin) {
- $this->pinyin = new Core('Overtrue\Pinyin\MemoryFileDictLoader');
- }
- return strtoupper(substr($this->pinyin->abbr($str, PINYIN_KEEP_ENGLISH), 0, 1));
- }
- }
|