473,320 Members | 2,097 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

pretty_print meets var_dump() ?

I googled, but don't find anything...

I have some pretty hairy arrays and when I var_dump() I get an
unreadable mess.

Surely someone has already written a function which will take a
var_dump and structure it?

Let's say that I have nested arrays a, b & c, I would like some output

A
.......
......
B
......
......
C
.....
.....
.....
.....

If you see what I mean.

Does it already exist, or do I have to code it myself?

Thanks in advance for any reply.

Dec 20 '05 #1
2 13136
On 20 Dec 2005 02:13:10 -0800, "Baron Samedi" <Pa************@gmail.com> wrote:
I have some pretty hairy arrays and when I var_dump() I get an
unreadable mess.

Surely someone has already written a function which will take a
var_dump and structure it?

Does it already exist, or do I have to code it myself?


There's print_r which might be more to your taste.

Also see the user-contributed notes on the print_r page in the PHP online
manual.

You are surrounding the var_dump() with <pre></pre> tags, right? Because
var_dump does structure nested arrays in a very similar way to your diagram
anyway.

<?php
$a = array('a' => array('b', array('c', array('d'))));
print "<pre>";
var_dump($a);
print_r($a);
var_export($a);
print "</pre>";
?>

Output:

array(1) {
["a"]=>
array(2) {
[0]=>
string(1) "b"
[1]=>
array(2) {
[0]=>
string(1) "c"
[1]=>
array(1) {
[0]=>
string(1) "d"
}
}
}
}
Array
(
[a] => Array
(
[0] => b
[1] => Array
(
[0] => c
[1] => Array
(
[0] => d
)

)

)

)
array (
'a' =>
array (
0 => 'b',
1 =>
array (
0 => 'c',
1 =>
array (
0 => 'd',
),
),
),
)

--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Dec 20 '05 #2
Following on from Baron Samedi's message. . .
I googled, but don't find anything...

I have some pretty hairy arrays and when I var_dump() I get an
unreadable mess.

Surely someone has already written a function which will take a
var_dump and structure it?


Here are some functions for arrays and objects that are a bit more than
print_r(). You /don't/ need to be using the trace functionality to get
the layout functionality.
If you find yourself with highly nested objects then the last function
(DumpObjectAsTree) is handy but needs another 300+ lines of PHP code
from me (ask if you want it) and Tigra Tree - free from
www.softcomplex.com/products/tigra_menu_tree/)


<?php
/*
Debugging etc functions
-----------------------
Setting up some tracing is simple:
TraceOn();
...
Trace(...);
...
TraceShow(); or TraceShow('../test/trace.htm');

*/
#--------------------------------------------------------
function ArrayToTable($ay,$Colour='#f0f0f0'){
# Return a HTML table with the array in it
#--------------------------------------------------------
if(count($ay)==0){
return("No elements in array<br>\n");
exit;
}

$firstrow=TRUE;
$t="<br><table bgcolor=$Colour border=1>";
foreach($ay as $k=>$a){
if($firstrow){
if(is_array($a)){
$t .= "<tr><td>Ø</td>";
foreach($a as $r=>$v){$t .= "<td><b>$r</b></td>";}
$t .= "</tr>\n";
$firstrow=FALSE;
}
}

$t .= "<tr>";
$t .= "<td><b>$k</b></td>";
if(is_array($a)){
foreach($a as $v){
if(!$v){
$v='<pre>Ø</pre>';
}else{
if(is_object($v)){
$v='<i>'.get_class($v).'</i>';
}
}
$t .= "<td>$v</td>";
}
}else{
if(!$a){
$a='Ø';
}else{
if(is_object($a)){
$a='<i><font color=blue>•'.get_class($a).'</font></i>';
}
}
$t .= "<td>$a</td>";
}
$t .= "</tr>\n";
}
$t .= '</table><br>';
return $t;
}

#--------------------------------------------------------
function KeyListing($Array){
# Tabulate the keys of an array
#--------------------------------------------------------
print(ArrayToTable(array_keys($Array),'green'));
}
#--------------------------------------------------------
function FormattedExport($Var){
# Exported object with a bit of extra formatting
# Returns a string suitable for sending to screen
# See also {DumpObjectAsTree}
#--------------------------------------------------------
ob_start();
var_export($Var);
$s=ob_get_contents();
ob_end_clean();

$s=str_replace('<','&lt;',$s);
$s=str_replace('>','&gt;',$s);

$s=str_replace('class','<b>class</b>',$s);
$s=str_replace("= \n array (\n );",'= <i>MT()</i>',$s);
$s=str_replace("= \n array (",' = <b>array</b>(',$s);

$s=str_replace("\n ","\n| ¦ | ¦ | ¦ | <font
color=red>",$s);
$s=str_replace("\n ", "\n| ¦ | ¦ | ¦ <font
color=green>",$s);
$s=str_replace("\n ", "\n| ¦ | ¦ | <font color=blue>",$s);
$s=str_replace("\n ", "\n| ¦ | ¦ <font color=black>",$s);
$s=str_replace("\n ", "\n| ¦ | <font color=red>",$s);
$s=str_replace("\n ", "\n| ¦ <font color=green>",$s);
$s=str_replace("\n ", "\n| <font color=blue>",$s);
$s=str_replace("\n","\n<font>",$s);
$s=str_replace("\n","</font>\n",$s);
$s="<pre>$s</pre>";
return $s;

}
#-------- TRACE FUNCTIONS -----------------------

#----------------------------------------------------------
function TraceOn(){
# Switch trace recording on.
# See TraceReset()
#----------------------------------------------------------
$_SESSION['TRACE']=1;
}

#----------------------------------------------------------
function TraceOff(){
# Switch trace recording off.
#----------------------------------------------------------
if($_SESSION['TRACE']==1){unset($_SESSION['TRACE']);}
}

#----------------------------------------------------------
function Trace($Label,$ToBeTraced='Ø',$HTMLsafe=TRUE,$Cond ition=TRUE){
# Main trace call
# Only records trace if (a) recording=on and (b) Condition is true
# {Label} is required and is a simple string that tags the report
# If ** appears in the label then insert a horiz-rule in report
# If * appears in the label then show as bold
# {ToBeTraced} can be one of three things
# * String - report string
# * Array - list array
# * Object - report object's contents
# {Condition} If this is false then don't record
#----------------------------------------------------------

// test to see if anything to do
if($Condition){
if(isset($_SESSION['TRACE'])){
// label with special flags
$lab=str_replace('**','',$Label);
if($lab!=$Label){
$t='<hr>'.$lab;
}else{
$lab=str_replace('*','',$Label);
if($lab!=$Label){
$t="<font color=green><b>$lab</b></font>";
}else{
$t="<font color=green>$lab</font>";
}
}
$lab = $t;
// list the array elements in one string
$t='';
if(is_array($ToBeTraced)){
$t .= ArrayToTable($ToBeTraced);
}else{
// dump a complete object
if(is_object($ToBeTraced)){
$ob= ''; $cb='';
$t .= $ob . FormattedExport($ToBeTraced);
}else{
// literal text
$ob= '('; $cb=')<br>';
$t .= $ToBeTraced;
}
if($HTMLsafe){
$t=str_replace('<br>','••',$t);
$t=htmlspecialchars($t);
$t=str_replace('••','<br>',$t);
}
}
$_SESSION['TRACELOG'] .= "<br>$lab ($t)";
}
}
}
#----------------------------------------------------------
function TraceReset(){
# Switch recording on AND clear the recording
#----------------------------------------------------------
TraceOn();
$_SESSION['TRACELOG']='';
}
#----------------------------------------------------------
function TraceShow($FileName=''){
# Produce report in HTML format
# Clears the recording afterwards
# Does not do anything if there is nothing to report. (So
# is OK to leave in when tracing is switched off.)
# If {FileName} is blank then print to screen
#----------------------------------------------------------

// don't do anything unless something to report
if(isset($_SESSION['TRACELOG'])){
$t=$_SESSION['TRACELOG'];
if($t){

// heading
$d=date('H:i:s');
$t="<b>~~~TRACE~~~</b>$d".$t."<br>\n";

// possibly write to file...
if($FileName){
$f=fopen($FileName,'w');
if($f){
fwrite($f,$t);
fclose($f);
}
}else{
// ... or print to screen
print($t);
}
// clear the log
$_SESSION['TRACELOG']='';
}
}
}

#----------------------------------------------------------
function TimeStampStr($Mode=0){
# Return a timestamp in pretty string.
# Default format is H:i:s
# {Mode} 1 ... j M y H:i:s
# {Mode} 2 ... j M y H:i
#----------------------------------------------------------
switch($Mode){
case 1 : $f= 'j M y H:i:s'; break;
case 2 : $f= 'j M y H:i'; break;
default : $f= 'H:i:s'; break;
}
return date($f);
}
#----------------------------------------------------------
function DumpObjectAsTree($SomeObject,$DestinationFile){
# Write the object in detail to the specified file
# This is presented in the form of an expandable tree
# See also {FormattedExport()} for simpler (in-line) version
#----------------------------------------------------------

// get PHP to report the object
ob_start();
var_export($SomeObject);
$s=ob_get_contents();
ob_end_clean();

// global tidy up and reformat
$s=str_replace("'",'"',$s);
$s=str_replace('<','&lt;',$s);
$s=str_replace('>','&gt;',$s);
$s=str_replace("array (\n );",'<i>MT()</i>',$s);
$s=str_replace('class','<b>object</b>',$s);
$s=str_replace("public $",'$',$s);
$s=str_replace("private $",'$',$s);
$s=str_replace("protected $",'$',$s);
$s=str_replace("(\n","\n",$s);
$s=str_replace("{\n","\n",$s);
$s=str_replace(";\n","\n",$s);

// put into an array format
// then step through it weeding and combining
$a=explode("\n",$s); // source
$b=array(); // destination
$continued=FALSE; // does next source get added to this one
foreach($a as $s){
$ts=trim($s);

// skip closers
if( ($ts=='}') or ($ts=='},') or ($ts==')')) { continue; }

// write to dest
if($continued){ // add to last line
$i=count($b)-1;
$b[$i]=$b[$i].' '.$ts;
$continued=FALSE;
}else{ // new line
$b[]=$s;
}

// flag if the next item is to carry on on same line
$continued = ((substr($ts,-5) == '=&gt;') or (substr($ts,-1) ==
'='));

}

// Build the menu
$mnu = new menuTree();
$mnu->headerText=TimeStampStr();
$mnu->AddIndentedList($b,2);

// write to file
$fp = fopen($DestinationFile, 'w');
if($fp){
fwrite($fp,$mnu->CompleteMenu());
fclose($fp);
}

// tidy up these potentially large items
unset($mnu);
unset($a);
unset($b);

}

?>

--
PETER FOX Not the same since the submarine business went under
pe******@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.co.uk>
Dec 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Marek Kubica | last post by:
Hi! I was thinking about connecting SimpleXMLRPCServer with inetd.. but I haven't been able to replace the socket by sys.stdin and sys.stdout. Maybe socket.fromfd(sys.stdin.fileno()) could help...
13
by: Frank Wagner | last post by:
Hello NG! Though I´m not new to programming at all, i´m new to C++. got the following question/problem with it´s behaviour: - read number with *arbitrary number of digits* from keyboard...
0
by: JT | last post by:
Hi, I'm sure this isn't a hard one, can someone help? I'm adding a new record to a MySQL database every x seconds. I need to be able to inspect the content of a certain field in this incoming...
383
by: John Bailo | last post by:
The war of the OSes was won a long time ago. Unix has always been, and will continue to be, the Server OS in the form of Linux. Microsoft struggled mightily to win that battle -- creating a...
23
by: Mario T. Lanza | last post by:
I have been authoring web sites for several years now and recently come to value web standards (as touted by Zeldman and many other web gurus). I have noticed with frustration that there are so...
1
by: Scot Balfour | last post by:
I have an MS Access form that uses a tab control with multiple tabs. On each tab, there are various fields. How can I color-- or if easier add some simple icon--to a particular tab (say tab 2 of...
1
by: ChuckDemon | last post by:
Is there a .NET class or function to dump the contents of a variable/array/object/whatever to the console? Console.WriteLine( dump_variable( my_var ) ); Thanks.
3
by: Magnus | last post by:
I have a datatable (I will call it 'main' datatable) with records that have child rows. I need to select all the records from the main datatable where the record/row has a childrow that meets a...
3
by: jm.suresh | last post by:
Hi, I have a list and I want to find the first element that meets a condition. I do not want to use 'filter', because I want to come out of the iteration as soon as the first element is found. I...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.