Tuesday, 28 August 2018

PHP Echo a multidimensional array


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?

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;
    }
}

0 comments:

Post a Comment