Jump to content

looping through a multidimensional array


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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...