drci47425 2012-01-19 15:22 采纳率: 100%
浏览 90
已采纳

如何在php中使用printf格式化数组

I know the printf statement in PHP can format strings as follows:

//my variable 
$car = "BMW X6";

printf("I drive a %s",$car); // prints I drive a BMW X6, 

However, when I try to print an array using printf, there does not seem to be a way to format it. Can anyone help?

  • 写回答

5条回答 默认 最新

  • dongwu9647 2012-01-19 15:25
    关注

    Here's an extract from one of the comments on http://php.net/manual/en/function.printf.php:

    [Editor's Note: Or just use vprintf...]

    If you want to do something like:

    // this doesn't work
    printf('There is a difference between %s and %s', array('good', 'evil'));   
    

    Instead of

    printf('There is a difference between %s and %s', 'good', 'evil'); 
    

    You can use this function:

    function printf_array($format, $arr) 
    { 
        return call_user_func_array('printf', array_merge((array)$format, $arr)); 
    }  
    

    Use it the following way:

    $goodevil = array('good', 'evil'); 
    printf_array('There is a difference between %s and %s', $goodevil); 
    

    And it will print:

    There is a difference between good and evil
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路