漏刻有时API接口实战开发系列(7):PHP将API获取的json数据自动同步到mysql数据库的解决方案

通过API端口将获取JSON数据

   //执行获取json数据;
        $content = posturl($url, $data, $webAPI);
        $dataInfo = $content["data"];

将JSON数据同步到mysql数据库;

  1. 判断唯一ID,是否在数据库中存在;
  2. 存在,则执行更新操作;
  3. 不存在,则执行添加操作;
 //将数据复制到对应的数据库;
        for ($i = 0; $i < count($dataInfo); $i++) {
            //转换参数;
            $data_id = $dataInfo[$i]["_id"];
            $member_scan = $dataInfo[$i]["_widget_1599805656440"];
            $member_depart = $dataInfo[$i]["_widget_1599805500424"];
            $member_serial = $dataInfo[$i]["_widget_1599805500425"];
            $member_name = $dataInfo[$i]["_widget_1599805500426"];
            $member_nation = $dataInfo[$i]["_widget_1599805500427"];
            $member_uties = $dataInfo[$i]["_widget_1599805500428"];
            $member_driving = $dataInfo[$i]["_widget_1599805500429"];
            $member_grade = $dataInfo[$i]["_widget_1599805500430"];
            $member_birth = $dataInfo[$i]["_widget_1599805500431"];
            $member_enlist = $dataInfo[$i]["_widget_1599805500432"];
            $member_political = $dataInfo[$i]["_widget_1599805500434"];
            $member_native = $dataInfo[$i]["_widget_1599805500436"];
            $user_name = $dataInfo[$i]["creator"]["name"];
            $submit_time = strtotime($dataInfo[$i]["createTime"]);
            $update_time = strtotime($dataInfo[$i]["updateTime"]);

            //判断数据库中是否存在;
            $row = $db->fetch('battle', 'member_id,data_id', array('data_id' => trim(addslashes($dataInfo[$i]["_id"]))), ' member_id DESC');
            if (!$row) {//如果不存在数据,则新增数据;
                $db->insert('battle', array('data_id' => $data_id, 'member_scan' => $member_scan, 'member_depart' => $member_depart, 'member_serial' => $member_serial, 'member_name' => $member_name, 'member_nation' => $member_nation,
                    'member_uties' => $member_uties, 'member_driving' => $member_driving, 'member_grade' => $member_grade, 'member_birth' => $member_birth, 'member_enlist' => $member_enlist,
                    'member_political' => $member_political, 'member_native' => $member_native, 'user_name' => $user_name, 'submit_time' => $submit_time, 'update_time' => $update_time));
            } else { //如果已经存在改数据,则更新数据;
                $db->update('battle', array('member_scan' => $member_scan, 'member_depart' => $member_depart, 'member_serial' => $member_serial, 'member_name' => $member_name, 'member_nation' => $member_nation,
                    'member_uties' => $member_uties, 'member_driving' => $member_driving, 'member_grade' => $member_grade, 'member_birth' => $member_birth, 'member_enlist' => $member_enlist,
                    'member_political' => $member_political, 'member_native' => $member_native, 'user_name' => $user_name, 'update_time' => $update_time), "data_id='" . $row['data_id'] . "'");
            }
        }

Done!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页