...

View Full Version : Foreach help?



stfc_boy
12-21-2010, 12:52 PM
Hello All,

Have a quick question. I have a foreach statement that runs with a loop in order to produce some queries. Here's a snippett of it:



$i=1;
$users = array (3,4);
foreach ($users as $user) {

switch (TRUE) {
case ($i == 1) : $start='09:00:00';$end='09:30:00';break;
case ($i == 2) : $start='09:30:00';$end='10:00:00';break;
}

print $SQL = "SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 $start' AND estimated_end_time <= '2010-12-21 $end' AND user_id = $user"."<br />";

$i++;

}


Which prints as:



SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 09:00:00' AND estimated_end_time <= '2010-12-21 09:30:00' AND user_id = 3
SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 09:30:00' AND estimated_end_time <= '2010-12-21 10:00:00' AND user_id = 4


But what I want to do is loop ALL the queries for user_id = 3 and then run back and run the same queries for user_id = 4, so my printed queries look like:



SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 09:00:00' AND estimated_end_time <= '2010-12-21 09:30:00' AND user_id = 3
SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 09:30:00' AND estimated_end_time <= '2010-12-21 10:00:00' AND user_id = 3
SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 09:00:00' AND estimated_end_time <= '2010-12-21 09:30:00' AND user_id = 4
SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 09:30:00' AND estimated_end_time <= '2010-12-21 10:00:00' AND user_id = 4


Hope i've explained this OK? Anyone please offer any advice?

Thanks

Chris

poyzn
12-21-2010, 01:06 PM
try this


$users = array (3,4);
foreach ($users as $user) {
for($i = 1; $i <= 2; $i++) {
switch ($i) {
case 1 : $start='09:00:00';$end='09:30:00';break;
case 2 : $start='09:30:00';$end='10:00:00';break;
}
print $SQL = "SELECT * FROM `tbl` WHERE estimated_start_time >= '2010-12-21 $start' AND estimated_end_time <= '2010-12-21 $end' AND user_id = $user"."<br />";
}
}

stfc_boy
12-21-2010, 01:26 PM
Magic, Thanks.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum