Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

php - While and for loop not working

I have a question and I think there is a really easy solution for, but i'm busy for 12 hours now and I don't know the solution for this problem.

I have a database with several data. The important data is the time that I save in the database. I want to build a module that give the data 08:00 to 17:00. For example:

08:00 available
09:00 not available
10:00 available
11:00 available
12:00 available
13:00 available
14:00 available
15:00 available
16:00 available
17:00 not available

I'll using the following code

$mysql['avail'] = mysql_query("SELECT time FROM `module` WHERE `date` = '" . $dbdate . "' ORDER BY date");
while($avail = mysql_fetch_assoc($mysql['avail'])){

  $hour = date('s',$avail['time']);

  for ($i = 8;$i <= 17; $i++) {

    if($hour == $i) {

        echo $i.':00&nbsp;not available<br />';

    } else {


        echo $i.':00&nbsp;available<br />';

    }

  } 

}

Now I get the following output:

08:00 available
09:00 not available
10:00 available
11:00 available
12:00 available
13:00 available
14:00 available
15:00 available
16:00 available
17:00 available

08:00 available
09:00 available
10:00 available
11:00 available
12:00 available
13:00 available
14:00 available
15:00 available
16:00 available
17:00 not available

Whatever I try, I've no solution to get it right. Is there anybody that can help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to fetch all your available hours at first and then make one loop with your timetable and check for each hour if it is in available hours array.

Something like this one

$not_available_hours = array();
$mysql['avail'] = mysql_query("SELECT time FROM `module` WHERE `date` = '" . $dbdate . "' ORDER BY date");
while($avail = mysql_fetch_assoc($mysql['avail'])){
    $not_available_hours[] = date('s',$avail['time']);
}

for ($i = 8;$i <= 17; $i++) {
    if (in_array($i, $not_available_hours) {
        echo $i.':00&nbsp;not available<br />';
    } else {
        echo $i.':00&nbsp;available<br />';
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...