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 57 58 59 60 61 62 63 64 65 66 67 68
| protected $data;
protected $keys;
protected $result;
protected $typeList = [ 'pc', 'pca', 'pcas' ];
protected function update($type = 1) { $url = 'https://raw.githubusercontent.com/modood/Administrative-divisions-of-China/master/dist/' . $this->typeList[$type] . '-code.json';
$data = json_decode(file_get_contents($url), true);
$this->result = DB::table('district')->get();
$this->keys = $this->result->pluck('id')->toArray();
$this->getItem($data);
DB::table('district')->whereIn('id', $this->keys) ->delete();
return true; }
protected function getItem($data, $pid = 0) { foreach($data as $value) { if(isset($value['children'])) { $this->getItem($value['children'], $value['code']); }
$item = $this->result->firstWhere('id', $value['code']);
if($item) { array_splice($this->keys, array_search($value['code'], $this->keys), 1);
if($item->name !== $value['name'] || $item->pid !== $pid) { DB::table('district')->where('id', $value['code']) ->update([ 'name' => $value['name'], 'pid' => $pid ]); } } else { DB::table('district')->insert([ 'id' => $value['code'], 'name' => $value['name'], 'pid' => $pid ]); } } }
public function index() { $result = DB::table('district')->select('id', 'name') ->where('pid' , request('pid', 0)) ->get() ->toArray();
return response()->json($result); }
|