Jump to content

looping through a multidimensional array


jimfog

Recommended Posts

I am using a foreach loop within foreach to iterate through a multi-dimensional array.

foreach ($content as $key=>$v1) {   foreach ($v1 as $times) {            print_r($v1['day'].$v1['open'].$v1['close'].'<br>');    }}

this array is the seven weekdays and each weekday is another array containing the the open/close times of a store(13:00-14:00 for example)

It looks something like that...the first member for example

['monday']=>['day'=>'monday','open'=>'13:00','close'=>'14:00']

there are occasion where the store is closed and in the place of open/close there are empty strings....

 

despite though having the browser printing an empty string......the browser just prints the key name...Monday for example

 

why this happens?

Link to comment
Share on other sites

You don't seem to have used the variable $times anywhere. Since the weekday name is already the key, you don't need to also have it as a value.

 

It should be more like this:

foreach ($content as $day => $times) {       echo $day . ' ' .  $times['open'] . ' ' . $times['close'] . '<br>';}
Link to comment
Share on other sites

 

You don't seem to have used the variable $times anywhere. Since the weekday name is already the key, you don't need to also have it as a value.

 

It should be more like this:

foreach ($content as $day => $times) {       echo $day . ' ' .  $times['open'] . ' ' . $times['close'] . '<br>';}

Thanks...actually I was using times in another version of the code....something I had forgotten to do for the code you see in my post.

 

That other version of course is not what is displayed in your post....meaning my code was wrong either with times in it or without it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...