note 40053 deleted from function.print-r by aidan
| From: | aidan@php.net | Date: | Mon, 11 Oct 2004 13:06:44 +0000 |
| Subject: | note 40053 deleted from function.print-r by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-78338@lists.php.net to get a copy of this message | ||
Note Submitter: petermatuchniak at variousartist dot com
----
Here's an alternative method for printing out multi-dimensional arrays if you like to see where
each element is in the array from an index standpoint, with each element on a separate line, plus
breaks for each block of array items.
I have also included a quicker way of displaying the array on multiple lines using plain old print_r
as a comparison (although it lacks the indexing as in my code). I hope folks find this useful, and
I welcome any additional alternatives and/or improvements:
<?php
function tpm_array_split(&$out_str, $in_arr, $in_key=null, $in_lvl=0, $in_lvl_str=null )
{
$i=-1;
while(list($k, $v) = each($in_arr))
{
$i++;
if ($in_lvl_str == null) { $ls = "$i"; }
else { $ls = $in_lvl_str . "," . $i; }
if ((is_array ($v)) || ($this->newline))
{
$out_str .= "<br>"; //print "<br>";
}
$out_str .= "<br>[$ls][$k=$v]"; //print
"<br>[$ls][$k=$v]";
$this->newline = FALSE;
if (is_array ($v))
{
$l = $in_lvl+1;
tpm_array_split($out_str, $v, $k, $l, $ls);
$this->newline = TRUE;
}
else
{
$this->newline = FALSE;
}
}
}
$md_arr = array ( "fruit" => array ( "apple", "banana",
"orange")
, "person" => array ( "male" => array (
"child" => "boy", "adult" => "man" )
, "female" => array ( "child" => "girl",
"adult" => "woman" )
)
, "A" => "a", "B" => "b",
"C" => "c"
, "numbers" => array ( 10,25,36,43 )
);
tpm_array_split($out_str2, $md_arr);
print "<br>Using tpm_array_split: <br> " . $out_str2;
$out_str1 = nl2br(print_r($md_arr, true));
print "<br>Using print_r: <br> " . $out_str1;
?>
Using tpm_array_split:
[0][fruit=Array]
[0,0][0=apple]
[0,1][1=banana]
[0,2][2=orange]
[1][person=Array]
[1,0][male=Array]
[1,0,0][child=boy]
[1,0,1][adult=man]
[1,1][female=Array]
[1,1,0][child=girl]
[1,1,1][adult=woman]
[2][A=a]
[3][B=b]
[4][C=c]
[5][numbers=Array]
[5,0][0=10]
[5,1][1=25]
[5,2][2=36]
[5,3][3=43]
Using print_r:
Array
(
[fruit] => Array
(
[0] => apple
[1] => banana
[2] => orange
)
[person] => Array
(
[male] => Array
(
[child] => boy
[adult] => man
)
[female] => Array
(
[child] => girl
[adult] => woman
)
)
[A] => a
[B] => b
[C] => c
[numbers] => Array
(
[0] => 10
[1] => 25
[2] => 36
[3] => 43
)
)