G. McLeod G. McLeod - 9 months ago 60
PHP Question

How do I format print_r output using multi-dimensional array

I have a multi dimensional array as follows,

$March = array (
"Friday" => array(
"1st" => 3,
"2nd" => 10,
"3rd" => 17,
"4th" => 24,
"5th" => 31
),
"Saturday" => array (
"1st" => 4,
"2nd" => 11,
"3rd" => 18,
"4th" => 25
),
"Sunday" => array (
"1st" => 5,
"2nd" => 12,
"3rd" => 19,
"4th" => 26
),
"Monday" => array (
"1st" => 6,
"2nd" => 13,
"3rd" => 20,
"4th" => 27
),
"Tuesday" => array (
"1st" => 7,
"2nd" => 14,
"3rd" => 21,
"4th" => 28
),
"Wednesday" => array (
"1st" => 8,
"2nd" => 15,
"3rd" => 22,
"4th" => 29
),
"Thursday" => array (
"1st" => 9,
"2nd" => 16,
"3rd" => 23,
"4th" => 30
)


)

I would like to print the array out in the following format

[Friday] => Array ( [1st] => 3 [2nd] => 10 [3rd] => 17 [4th] => 24 [5th] => 31 )
[Saturday] => Array ( [1st] => 4 [2nd] => 11 [3rd] => 18 [4th] => 25 )
[Sunday] => Array ( [1st] => 5 [2nd] => 12 [3rd] => 19 [4th] => 26 )
[Monday] => Array ( [1st] => 6 [2nd] => 13 [3rd] => 20 [4th] => 27 )
[Tuesday] => Array ( [1st] => 7 [2nd] => 14 [3rd] => 21 [4th] => 28 )
[Wednesday] => Array ( [1st] => 8 [2nd] => 15 [3rd] => 22 [4th] => 29 )
[Thursday] => Array ( [1st] => 9 [2nd] => 16 [3rd] => 23 [4th] => 30 )


I can do this by using print_r($March); but it gives me this output

Array ( [Friday] => Array ( [1st] => 3 [2nd] => 10 [3rd] => 17 [4th] => 24 [5th] => 31 ) [Saturday] => Array ( [1st] => 4 [2nd] => 11 [3rd] => 18 [4th] => 25 ) [Sunday] => Array ( [1st] => 5 [2nd] => 12 [3rd] => 19 [4th] => 26 ) [Monday] => Array ( [1st] => 6 [2nd] => 13 [3rd] => 20 [4th] => 27 ) [Tuesday] => Array ( [1st] => 7 [2nd] => 14 [3rd] => 21 [4th] => 28 ) [Wednesday] => Array ( [1st] => 8 [2nd] => 15 [3rd] => 22 [4th] => 29 ) [Thursday] => Array ( [1st] => 9 [2nd] => 16 [3rd] => 23 [4th] => 30 ) )


I've figured out that I can print each of my arrays out with
print_r($March['Friday']);


But that only gives me this

Array ( [1st] => 3 [2nd] => 10 [3rd] => 17 [4th] => 24 [5th] => 31 )


which is not the same as this

[Friday] => Array ( [1st] => 3 [2nd] => 10 [3rd] => 17 [4th] => 24 [5th] => 31 )


plz send help, have been staring at w3 for hours.

Answer Source

To achive this what you write in comment you can use below loop:

foreach($March as $nameOfDay => $dayArray ){
    foreach($dayArray as $key => $val){
        echo $val.' is the '.$key.' '.$nameOfDay.' in March. ';
    }
}