Php 在打印输出前加上空白
在PHP中,我编写了一个函数,根据调试回溯中的深度缩进回显行:Php 在打印输出前加上空白,php,arrays,string,whitespace,prepend,Php,Arrays,String,Whitespace,Prepend,在PHP中,我编写了一个函数,根据调试回溯中的深度缩进回显行: function echon($string){ $nest_level = count(debug_backtrace()) - 1; // minus one to ignore the call to *this* function echo str_repeat(" ", $nest_level) . $string . "\n"; } 我在每个函数的开头使用它来帮助调试;例如, echon(“功能:数据库->插
function echon($string){
$nest_level = count(debug_backtrace()) - 1; // minus one to ignore the call to *this* function
echo str_repeat(" ", $nest_level) . $string . "\n";
}
我在每个函数的开头使用它来帮助调试;例如,echon(“功能:数据库->插入行”)代码>
我想为print\r
编写一个类似的函数,但我不确定如何编写。在查看打印文档后,我了解到传递可选参数true
会使其返回字符串,但该字符串的格式奇怪;如果我全速回显它,它看起来是这样的:
print\r
返回字符串为:
Array
(
[uid] => 1
[username] => user1
[password] => $2y$10$.XitxuSAaePgUb4WytGfKu8HPzJI94Eirepe8zQ9d2O1oOCgqPT26
[firstname] => devon
[lastname] => parsons
[email] =>
[group] =>
[validated] => 0
[description] =>
[commentscore] => 0
[numberofposts] => 0
[birthdate] => 1992-04-23
[location] =>
[signupdate] => 0000-00-00
[personallink] =>
)
所以我原本以为它会返回一个单行响应,我可以用同样的方式手动分解和缩进,但它是多行的,我不知道下一步要查找什么。我在php文档中查找字符串,看看是否有某种方法可以一次提取一行,或者根据新行将其分解,但我没有发现任何内容,谷歌也没有发现任何类似的内容
问题:如何在打印的结果前加上空格
编辑:示例desire输出(假设我从深度1调用我的函数)
这应该满足您的要求:
function print_rn($array)
{
$nest_level = count(debug_backtrace()) - 1; // minus one to ignore the call to *this* function
$lines = explode("\n", print_r($array, true));
foreach ($lines as $line) {
echo str_repeat(" ", $nest_level) . $line . "\n";
}
}
说明:
print\r
接受第二个参数,该参数允许您返回值,而不是将其打印出来。然后,您可以使用explode
函数(这是PHP的string\u split函数)在每个换行处将返回的字符串拆分为一个数组。现在您有了一个行数组
有了一个行数组,就可以简单地遍历每一行并使用适当的空白量打印它
function print_rn($array)
{
$nest_level = count(debug_backtrace()) - 1; // minus one to ignore the call to *this* function
$lines = explode("\n", print_r($array, true));
foreach ($lines as $line) {
echo str_repeat(" ", $nest_level) . $line . "\n";
}
}