将迭代次数转换为有限范围(如星期几)

时间:2016-07-04 11:24:25

标签: php range limit

我需要将迭代次数转换为1到7之间的范围。

$y = keepInRange(1, 7, $i)

结果输入 - >输出预计如下

  • 1 - > 1
  • ...
  • 7 - > 7
  • 8 - > 1
  • 9 - > 2
  • ...
  • 14 - > 7
  • 15 - > 1

我已经尝试了以下但没有成功:

min(7, max(1, $numberToStr[$i])) (all output 1)
$y = $i % 7 (all outputs 0, Edit: this was a mistake by me, its the solution when +1 is added.)

2 个答案:

答案 0 :(得分:2)

尝试:

$day_of_week = $num <= 7 ? $num : $num % 7;

演示:

for($num=1; $num<25; $num++) {
    $day_of_week = $num <= 7 ? $num : $num % 7;
    echo '<p>'.$num.': '.$day_of_week.'</p>';
}

Demo in JS

答案 1 :(得分:2)

试试这个

<?php
$num = 15;
$res= $num%7;
if($res == 0)
{
    echo "7";
}
else
{
    echo $res;
}

https://3v4l.org/dDGs3

我希望它会有所帮助