dpnvrt3119 2016-03-28 16:39
浏览 35
已采纳

如果字符串为空,请让php sprintf省略return

I am wresting with printing shipping labels and getting the final output to omit a second address line if one exists. Is there a way to conditionally exclude the line break if $address2 is empty when using sprintf()?

            while($rows=mysql_fetch_array($result)){
                $name = $rows['address_name'];
                $address = $rows['street1'];
                $address2 = $rows['street2'];
                $citystatezip = $rows['city'].', '.$rows['state'].' '.$rows['zip'];
                $country = $rows['country'];
                $text = sprintf("%s
%s
%s
%s
", $name, $address, $address2, $citystatezip, $country);
                $pdf->Add_Label($text);
            }
  • 写回答

1条回答 默认 最新

  • douya1061 2016-03-28 17:22
    关注

    Your sprintf only has 4 '%s' and 5 params.

    In this code, I removed the from the sprintf into a conditional above.

            // Don't use mysql_xxxx functions
            // Should really be using PDO       
            //          +---------------+
            //          |               |
            while($rows=mysql_fetch_array($result)){
                $name = $rows['address_name'];
                $address = $rows['street1'];
                $address2 = $rows['street2'];
                $citystatezip = $rows['city'].', '.$rows['state'].' '.$rows['zip'];
                $country = $rows['country'];
                $addr2 = empty($address2) ? '' : $address2 . "
    ";
                $text = sprintf("%s
    %s
    %s%s
    %s
    ", $name, $address, $addr2, $citystatezip, $country);
                $pdf->Add_Label($text);
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度