把百分号(%)符号替换成一个作为参数进行传递的变量:
<?php $number = 2; $str = "Shanghai"; $txt = sprintf("There are %u million cars in %s.",$number,$str); echo $txt; // There are 2 million cars in Shanghai. ?>
经典代码案例:(经过删减之后有逻辑错误,只要本博主知道大体意思即可,其他人不要看该案例)
/** *处理到期年份 * $tableid:字符串 * $where:筛选需要修改的档案的where条件 */ public function updateExpireyear($idArr){ $emptyList = array(); $when = ''; $when_sql = "when %s then '%s' "; $em_sql = "when %s then %s "; foreach($docList as $k=>&$docone){ $tmp = sprintf($when_sql,$docone['id'],$docone['expireyear']); $when = $when.$tmp; } if(!empty($emptyList)){ foreach($emptyList as $emone){ $emtmp = sprintf($em_sql,$emone['id'],$emone['expireyear']); $when = $when.$emtmp; } } $sql = "UPDATE {$tableid} SET `expireyear` = CASE id ".$when." END WHERE `id` in ({$ids}) "; $result = $this->getProxy('db')->execute($sql); }
传入参数:
array(1527844078575627623,1520502796098626275)
执行sql查询:
UPDATE f1_14_document SET `expireyear` = CASE id when 1520502796098626275 then '15' when 1527844078575627623 then '10' END WHERE `id` in (1520502796098626275,1527844078575627623)
这里使用sprintf 拼凑出了 “when 1520502796098626275 then '15' when 1527844078575627623 then '10'”