PHP Echo一个多维数组

时间:2012-12-01 05:37:04

标签: php mysql

我有一个多维数组,当我使用print_r时,如下所示:

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 
                ) 
 ) 

这是父/子多维数组。可以有任意数量的父母和任何数量的孩子。

如何回显多维数组,使其看起来像这样

Car
    Camry 
    Lexus 
    honda 
    toyota

Job
    Bookstore
    Cafe

City
    Wisconsin
    Chicago
    New York City
    Los Angeles

我尝试打印多维数组:

function RecursiveWrite($array) {
                      foreach ($array as $vals) {
                          echo $vals['parent'] . "\n";
                          RecursiveWrite($vals['child']);
                      }
                  }     
RecursiveWrite($categories); // $categories is the name of the array 

运行代码时,这不会输出任何输出。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

考虑到制表符和返回符号取决于你想要的HTML或FILE输出,它是代码:

$tab = "\t"; // tab
$return = "\r"; // return

foreach ($array as $key => $a) {
    echo $key.$return;
    foreach ($a as $value) {
        echo $tab.$value.$return;
    }
}

答案 1 :(得分:1)

创建递归函数:

半伪:

function dumpArr (arr){
  foreach element in arr {
    if element is array/object{
      dumpArr(element)
    }else{
      echo element
    }
  }
}

然后,您可以使用CSS来调整填充,边距等

答案 2 :(得分:0)

以下代码可以显示:

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