Reputation: 2533
I have a multidimensional array that when i use print_r looks like this:
Array (
[car] => Array (
[72] => Camry
[62] => Lexus
[55] => honda
[44] => toyota
)
[Job] => Array (
[70] => Bookstore
[73] => Cafe
)
[City] => Array (
[68] => Wisconsin
[63] => Chicago
[47] => New York City
[46] => Los Angeles
)
)
This is a Parent/Child Multidimensional array. There can be any number of parents, and any number of children.
How do I echo out a multidimensional array so that it looks like this
Car
Camry
Lexus
honda
toyota
Job
Bookstore
Cafe
City
Wisconsin
Chicago
New York City
Los Angeles
My attempt at printing a multidimensional array out:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['parent'] . "\n";
RecursiveWrite($vals['child']);
}
}
RecursiveWrite($categories); // $categories is the name of the array
This doesn't print out any output when I run the code. Any suggestions?
Upvotes: 0
Views: 879
Reputation: 21
the below code shows as you want:
<?php
$arrayToPrint = Array (
'car' => Array (
'72' => 'Camry',
'62' => 'Lexus',
'55' => 'honda',
'44' => 'toyota'
),
'Job' => Array (
'70' => 'Bookstore',
'73' => 'Cafe'
) ,
'City' => Array (
'68' => 'Wisconsin',
'63' => 'Chicago' ,
'47' => 'New York City',
'46' => 'Los Angeles'
)
) ;
echo "output in print_r( ):<pre>";
print_r($arrayToPrint);
echo "</pre>";
echo "output in echo:<br/>";
foreach($arrayToPrint as $arrayKey=> $arrayValue1) {
echo '<pre>';
echo $arrayKey;
foreach($arrayValue1 as $leafNodeValue) {
echo '<pre> '.$leafNodeValue.'</pre>';
}
echo '</pre>';
}
?>
Upvotes: 0
Reputation: 4164
Create a recursive function:
Semi-psuedo:
function dumpArr (arr){
foreach element in arr {
if element is array/object{
dumpArr(element)
}else{
echo element
}
}
}
then, you can use CSS to adjust the padding, margin, etc
Upvotes: 1
Reputation: 76240
Considering that the tab and return symbols depends on whatever you want an HTML or FILE output here it is the code:
$tab = "\t"; // tab
$return = "\r"; // return
foreach ($array as $key => $a) {
echo $key.$return;
foreach ($a as $value) {
echo $tab.$value.$return;
}
}
Upvotes: 1