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


How to format array out with printf in php

我知道PHP中的printf语句可以格式化字符串如下:

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

然而,当我尝试使用printf打印数组时,似乎没有格式化的方法。有人能帮忙吗?

以下是http://php.net/manual/en/function.printf.php:

[编者按:或者只使用vprintf…]

如果你想做一些类似的事情:

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

代替

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

您可以使用此功能:

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

按以下方式使用:

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

它将打印:

There is a difference between good and evil

您是否正在使用带有true参数的print_r来寻找类似的东西:

printf("My array is:***'n%s***'n", print_r($arr, true));

不能像那样"打印"数组,必须使用foreach对其进行迭代,然后才能使用值打印出所需的所有值。例如:

$cars = array('BMW X6', 'Audi A4', 'Dodge Ram Van');
foreach($cars as $car) {
    printf("I drive a %s", $car);
}

这将输出:

I drive a BMW X6

I drive a Audi A4

I drive a Dodge Ram Van

yes

在你的html位置这个:

<pre>
  <?php 
   print_r ($your_array);
  ?>
</pre>

或在您的代码专用位置:

 print_r ($your_array);

printf不递归处理数组。然而,您可以这样做:

$cars=array('Saab','Volvo','Koenigsegg');
print_r($cars);