基本功的重要作者:luke

$sqlJson = '
[
 {
  "query": "select * from `copy_user` where `copy_user`.`id` = ? and `copy_user`.`deleted_at` is null limit 1",
  "bindings": [
   1697
  ],
  "time": 2.87
 },
 {
  "query": "select `is_admin` from `hospital_areas` where `hospital_areas`.`id` = ? limit 1",
  "bindings": [
   1
  ],
  "time": 0.55
 },
 {
  "query": "select count(*) as aggregate from `kd_report_spec` as `r` left join `sp_case_info` as `p` on `p`.`uuid` = `r`.`case_id` left join `hospitals` as `h` on `h`.`uuid` = `r`.`hosp_id` where `r`.`published` = ?",
  "bindings": [
   1
  ],
  "time": 530.4
 },
 {
  "query": "select `p`.`patient_name`, `p`.`check_time`, `p`.`age_first_val` as `age`, `p`.`sex`, `p`.`outpatient`, `p`.`doctor`, `p`.`department_name`, `p`.`case_type`, `p`.`card_no`, `p`.`created_at` as `receive_time`, `r`.*, `h`.`hosp_name` from `kd_report_spec` as `r` left join `sp_case_info` as `p` on `p`.`uuid` = `r`.`case_id` left join `hospitals` as `h` on `h`.`uuid` = `r`.`hosp_id` where `r`.`published` = ? order by `r`.`created_at` desc limit 20 offset 0",
  "bindings": [
   1
  ],
  "time": 121.53
 },
 {
  "query": "select * from `conf_items` where `code` = ? limit 1",
  "bindings": [
   42000
  ],
  "time": 0.59
 },
 {
  "query": "select `r`.`state`, COUNT(r.id) as total from `kd_report_spec` as `r` left join `sp_case_info` as `p` on `p`.`uuid` = `r`.`case_id` left join `hospitals` as `h` on `h`.`uuid` = `r`.`hosp_id` where `r`.`published` = ? group by `r`.`state` order by `r`.`created_at` desc limit 100 offset 0",
  "bindings": [
   1
  ],
  "time": 563.73
 },
 {
  "query": "select count(*) as aggregate from `kd_report_spec` as `r` left join `sp_case_info` as `p` on `p`.`uuid` = `r`.`case_id` where `r`.`published` = ?",
  "bindings": [
   1
  ],
  "time": 326.58
 },
 {
  "query": "select `r`.`state`, COUNT(r.state) as total from `kd_report_spec` as `r` left join `sp_case_info` as `p` on `p`.`uuid` = `r`.`case_id` where `r`.`published` = ? group by `r`.`state` limit 100 offset 0",
  "bindings": [
   1
  ],
  "time": 298.87
 },
 {
  "query": "select count(*) as aggregate from `kd_report_spec` as `r` left join `sp_case_info` as `p` on `p`.`uuid` = `r`.`case_id` where `r`.`published` = ? and `r`.`print_times` = ?",
  "bindings": [
   1,
   0
  ],
  "time": 138.61
 }
]
';  
$arr = json_decode($sqlJson, true);
$cost = 0;
foreach($arr as $k=> $v){
 $sql = str_replace('?', '%s', $v['query']);
 $len = substr_count($sql, '%s');
 $params = $v['bindings'];
 // if($len ==1){
  // $sql = sprintf($sql, $params[0]);
 // }else if($len == 2){
  // $sql = sprintf($sql, $params[0], $params[1]);
 // }else if($len == 3){
  // $sql = sprintf($sql, $params[0], $params[1], $params[2]);
 // }
 $sql = vsprintf($sql, $params);#不会用vsprintf的可怜虫就会用上面的代码
 echo sprintf('%s;#sql%s cost %s ms %s', $sql, $k+1, $v['time'],PHP_EOL);
 $cost+= $v['time'];
}
echo sprintf('%s Total cost %s ms %s',PHP_EOL, $cost, PHP_EOL);
时间:2020-9-17 分类:练习