query()->insertGetId($data); // 失败返回0 if( !$id ) return 0; // 返回结果 return $id; } /** * 添加数据 * */ public function edit($id,$data) { // 更新时间 $data['update_time'] = time(); // 写入数据表 $result = $this->query()->where([['id','=',$id]])->update($data); // 失败返回0 if( !$result ) return 0; // 返回结果 return $id; } /** * 获取列表 * @param Bool $force 是否强制更新 * */ public function getList($force = false) { // 结果数据 $list = $force ? [] : cache('admin:city:list'); // 不存在数据 if ( !$list ) { // 从数据库获取数据 $data = $this->query()->where([['status','=',0],['level','<',3]])->get(['id','name','pid']); // 是否有数据 $data = $data ? $data->toArray() : []; // 循环处理数据 $list = []; // 进行更新 foreach ($data as $value) { // 重组数据 $list[$value['id']] = $value; } $list = $this->getTree($list); // 存起来 cache(['admin:city:list'=>$list]); } // 返回结果 return $list; } /** * 获取某个 * * @param int $id ID * @param string $field 指定字段 * */ public function getOne($id,$field='') { // 获取列表数据 $list = $this->getList(); // 获取数据 $one = isset($list[$id]) ? $list[$id] : []; // 返回值 return empty($field) ? $one : ( isset($one[$field]) ? $one[$field] : null); } /** * 获取城市对应的ID * * @param string $name 城市名 * */ public function getIdByName($name){ // 返回结果 return (int) $this->query()->where([['name','=',$name]])->value('id'); } /** * 获取城市列表 * */ public function getCityList(){ // 城市json $cityList = @file_get_contents(resource_path('./js/').'city.json'); // 解码 $cityList = (array) json_decode($cityList,true); // 返回结果 return $cityList; } /** * 无限极分类 * @param type $array * @return type $new_array */ public function getTree($array) { //遍历数组,按照id作为键名重新组建新的数组 $new_array = []; foreach ($array as $v) { $new_array[$v['id']] = $v; } //遍历新的数组,对每一个值的pid进行判断,判断新数组中是否存在键名为pid的值,如果存在,当前值为存在的pid的子节点,不存在,当前值为一级节点,添加到返回的数据中作为一级节点。这里使用引用传值是因为直接传值是不会影响到函数外边的变量值,我们这里要给一级节点添加子节点(sons),所以需要用到引用传值。 $return_tree = []; foreach ($new_array as $kk => $vv) { if (isset($new_array[$vv['pid']])) { $new_array[$vv['pid']]['sons'][] = &$new_array[$kk]; } else { $return_tree[] = &$new_array[$kk]; } } return $return_tree; } }