打印Multidimentional PHP数组

时间:2016-07-13 08:09:35

标签: php arrays

$arr_cont = array('type1' =>"Fruits",'f_div'=>
                    array(

                         1 => "Apple",
                         2 => "Banana",
                         3 => "Mango",
                         4 => "Grapes",
                         )
                        ,
            'type2' => "colors",'c_div' =>
                    array (
                            1 => "Red",
                            2 => "Green",
                          )
                        ,
            'type3' => "Shapes",'s_div' =>
                    array(
                            1 => "Square",
                            2 => "Round",   
                            )
                        ,
            'type4' => "Flowers",'l_div' =>
                    array(
                            1 => "Rose",
                            2 => "Lily",
                        )

            );

我有上面提到的数组,我想要输出如下,请给我这个foreach循环的complete编码

输出:

type1 : Fruits : f_div
1. Apple
2. Banana
3. Mango
4. Grapes
type2 : colors :c_div 
1. Red
2. Green
type3 : Shapes : s_div
1. Square
2. Round
type4 : Flowers : l_div
1. Rose
2. Lily

先谢谢...每个答案都会被评估......

我已经尝试了下面提到的代码,但它给出了一些错误:

foreach($arr_cont as $val => $cont){
    print $val ." : " ;
    foreach($cont as $val1 => $id){
       print $id ." : ".$val1;
}

错误消息

Warning: Invalid argument supplied for foreach() in 

但是它打印$ arr_cont变量以及错误 错误是在第二个foreach循环中

2 个答案:

答案 0 :(得分:0)

<?php

$arr_cont = array(
    'type1' => "Fruits",
    'f_div' =>
    array(
        1 => "Apple",
        2 => "Banana",
        3 => "Mango",
        4 => "Grapes",
    )
    ,
    'type2' => "colors",
    'c_div' =>
    array(
        1 => "Red",
        2 => "Green",
    )
    ,
    'type3' => "Shapes",
    's_div' =>
    array(
        1 => "Square",
        2 => "Round",
    )
    ,
    'type4' => "Flowers",
    'l_div' =>
    array(
        1 => "Rose",
        2 => "Lily",
    )
);
$output = "";
foreach ($arr_cont as $val => $cont) {
    if (is_array($cont)) {
        $output .= "$val<br />";
        foreach ($cont as $contIndex => $contValue) {
            $output .= " $contIndex. $contValue<br />";
        }
    } else {
        $output .= "$val : $cont : ";
    }
}
echo $output;

输出:

type1 : Fruits : f_div
1. Apple
2. Banana
3. Mango
4. Grapes
type2 : colors : c_div
1. Red
2. Green
type3 : Shapes : s_div
1. Square
2. Round
type4 : Flowers : l_div
1. Rose
2. Lily

答案 1 :(得分:0)

$ output = null;

foreach($ arr_cont as $ val =&gt; $ cont){

if (is_array($cont)) {

    $output .= $val.'<br/>';
    foreach ($cont as $contIndex => $contValue) {
        $output .=  $contIndex.' '. $contValue.'<br/>';
    }
} else {
    $output .= $val .':'. $cont.':';
}

} echo $ output;