简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM