php for循环语法:如何强加多个条件

For a daily calendar application, I want to print out the hours of the day from nine in the morning to eight at night. I am using the following syntax which works up through 12. However, then I want to restart the numbering on 1 and have it continue to 8. I know this could be done in a more complicated way with multiple if then expressions and so forth but hoping there is a clean way to do it with one elegant expression. This is partly because there is a database query in the midst of this that I would like to write out only once. Here is basic code:

PHP
//following works up to 12
for($hourofday = 9; $hourofday <= 12; $hourofday++): 

//I want to do something like following but the following does not work.

//for($hourofday = 9; $hourofday <= 12 || $hourofday >=1 && $hourofday <=8); $hourofday++): 
    $output.= $hourofday.':00';
//This is where dbase is queried for events and there is formatting so it looks like a calendar

endfor

Thanks for any suggestions!

You could do this:

for($hourofday=9; $hourofday <= 20; $hourofday++)
{
    if($hourofday > 12)
        $output .= $hourofday - 12 . ':00';
    else
        $output .= $hourofday . ':00';
}

or the shorter but harder to read way:

for($hourofday=9; $hourofday <= 20; $hourofday++)
{
    $output .= ($hourofday - ($hourofday > 12 ? 12 : 0)) .':00 ';
}
for($hourofday = 9; ; $hourofday = $hourofday%12 +1):
    //do whatever you want, then the last line:
    if($hourofday === 8) break;
endfor

It would be much better to loop over the hours using a 24-hour model and use the modulo operator to reduce to the 1-12 range in order to display:

for ($hourofday = 9; $hourofday <= 20; $hourofday++): 
    $displayhour = $hourofday % 12 ?: 12;
    echo $displayhour.":00
";
endfor;

See it in action.

Modulo 12 puts the hour in the [0, 11] range, but we want to display 0 as 12 -- that's where the ternary operator ?: comes in.

You can easily extend the logic to print AM/PM by simply checking if $hourofday is less than 12 or not.

I want 9am to 12PM and then 1PM to 8PM

In that case you should start at 9 and end at 20, and take the modulus by 12 when outputting.

What about this?

for($hourofday = 9; $hourofday <= 20; $hourofday++):
  $hr = ($hourofday > 12)?$hourofday-12:$hourofday;
  $output.= $hr.':00';
endfor