准备空白以打印输出(_r)


Prepend whitespace to print_r output

在PHP中,我编写了一个函数,根据调试回溯中的深度缩进echo'ed行:

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: Database->insert_row");

我想为print_r编写一个类似的函数,但我不确定如何编写。在查看了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文档中查找字符串,看看是否有办法一次提取一行,或者根据新行将其分解,但我一无所获,谷歌搜索也没有找到类似的内容。

问题:如何在print_r的结果前加空格?

编辑:示例愿望输出(假设我从深度1调用我的函数)

    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] => 
    )

这应该可以实现您想要的:

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_split函数)在每一个换行符处将返回的字符串拆分为一个数组。现在您有了一个行数组。

使用一个行数组,可以简单地对每一行进行迭代,并使用适当数量的空白进行打印。