gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:48:58 25 4
gpt4 key购买 nike

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

//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

关于php - 如何在php中用printf格式化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8928592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com