Jump to content

Archived

This topic is now archived and is closed to further replies.

dadamssg87

foreach multidimensional array

Recommended Posts

I've never worked with multidimensional arrays. I have developed a calendar app. Right now i have it query the db for every day. So potentially 31 queries. Two part question: Would it be better(more "optimized") to query the db once to get all the events in that month for a certain calendar and put the rows into a multidimensional array and use php to determine which events to put in what days? And if that's the case, how do you cycle through the first key in an array like the following? I'm not even sure if this is the best way to structure the array. The number's represent the id number in the db and i will need to cycle through these.

 

$events = array
  (
  "1"=>array
  (
  "Bob's Birthday",
  "2011-05-24 16:30:0",
  "2011-05-25 12:00:00",
  ),
  "2"=>array
  (
   "Day Off",
  "2011-05-27 08:30:0",
  "2011-05-28 17:00:00",
  ),
  "3"=>array
  (
   "Pay rent",
  "2011-06-01 08:00:0",
  "2011-05-01 17:00:00",
  )
  );


//something like this...maybe?

foreach($events['first_key'] as $key => $value) 
{
   // not a clue how to reference the contents
}

 

Share this post


Link to post
Share on other sites

You can use nested foreach loops to loop through a multidimensional array. FOr example

foreach( $events as $row){
  //now going through each row. This is basically the array of each days event info
  foreach($row as $column){
    //now we have each individual piece of information on the event
  }
}

 

hope this helps

Share this post


Link to post
Share on other sites

alright thanks, that makes sense. Is doing it with an array using one query significantly better than using 31 queries for each day? I'd be using timestamps and comparisons to do the determining rather than sql.

Share this post


Link to post
Share on other sites

yes doing 1 query is far better and far easier on your system then doing 31

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.