php print_r 漂亮的表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1386331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php print_r nice table
提问by Adam Chetnik
I'm looking to be able to produce a nicely formatted table with rows and columns from the contents of a print_r array statement?
我希望能够从 print_r 数组语句的内容生成一个格式良好的表,其中包含行和列?
Any ideas?
有任何想法吗?
回答by Kimzu
Here is a very simple way to print pretty arrays with html pre tag:
这是使用 html pre 标记打印漂亮数组的一种非常简单的方法:
<?php
$myarray = array('a','b','c');
echo '<pre>';
print_r($myarray);
echo '</pre>';
?>
回答by troelskn
Your question is a bit vague, but did you mean something like this:
你的问题有点含糊,但你的意思是这样的:
回答by JasonDavis
Try this out, could be improved but it works.
试试这个,可以改进,但它有效。
function myprint_r($my_array) {
if (is_array($my_array)) {
echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
foreach ($my_array as $k => $v) {
echo '<tr><td valign="top" style="width:40px;background-color:#F0F0F0;">';
echo '<strong>' . $k . "</strong></td><td>";
myprint_r($v);
echo "</td></tr>";
}
echo "</table>";
return;
}
echo $my_array;
}
回答by Vissie
Here is another nice example that I found. Same output, longer code, little bit more color.
这是我发现的另一个很好的例子。相同的输出,更长的代码,更多的颜色。
function print_nice($elem,$max_level=10,$print_nice_stack=array()){
if(is_array($elem) || is_object($elem)){
if(in_array(&$elem,$print_nice_stack,true)){
echo "<font color=red>RECURSION</font>";
return;
}
$print_nice_stack[]=&$elem;
if($max_level<1){
echo "<font color=red>nivel maximo alcanzado</font>";
return;
}
$max_level--;
echo "<table border=1 cellspacing=0 cellpadding=3 >";
if(is_array($elem)){
echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
}else{
echo '<tr><td colspan=2 style="background-color:#333333;"><strong>';
echo '<font color=white>OBJECT Type: '.get_class($elem).'</font></strong></td></tr>';
}
$color=0;
foreach($elem as $k => $v){
if($max_level%2){
$rgb=($color++%2)?"#888888":"#BBBBBB";
}else{
$rgb=($color++%2)?"#8888BB":"#BBBBFF";
}
echo '<tr><td valign="top" style="width:40px;background-color:'.$rgb.';">';
echo '<strong>'.$k."</strong></td><td>";
print_nice($v,$max_level,$print_nice_stack);
echo "</td></tr>";
}
echo "</table>";
return;
}
if($elem === null){
echo "<font color=green>NULL</font>";
}elseif($elem === 0){
echo "0";
}elseif($elem === true){
echo "<font color=green>TRUE</font>";
}elseif($elem === false){
echo "<font color=green>FALSE</font>";
}elseif($elem === ""){
echo "<font color=green>EMPTY STRING</font>";
}else{
echo str_replace("\n","<strong><font color=red>*</font></strong><br>\n",$elem);
}
}
}


