我需要帮助完成这项任务。
我需要一个选择最接近的持续时间的for循环
样本我们有120秒的持续时间120秒是每次计算除以8 所以这是一个例子
120持续时间
以下是8个最接近的值 15 三十 45 60 75 90 105 120
我怎么能意识到这一点我已经测试过了
<?php
$count = 1;
$duration = 120;
$temp = 0;
for ($x = 1; $x < 120; $x++) {
#$j = $x / 8;
$temp = $x / 8;
echo '<pre>' . ($temp) . '</pre>';
if ($count == 8) {
break;
}
$count++;
}
?>
答案 0 :(得分:2)
你的整个循环完全是多余的。为什么不呢:
<?php
for ($i = 0; i < 8; ++$i)
{
echo '<pre>' . (15 * ($i+1)) . '</pre>';
}
?>
您可以直接使用$i
作为循环中的计数器。
答案 1 :(得分:1)
你的意思是
$result = array();
for ($i = 1; $i <= 8; $i++) {
$result[] = (int) ($duration / 8) * $i;
}
答案 2 :(得分:1)
会有以下工作吗?
function sample($max, $count) {
$samples = array();
for($i = 1; $i <= $count; ++i) {
$samples[] = (int)($max / $count * $i);
}
return $samples;
}
答案 3 :(得分:1)
您的问题非常不明确,所提供的代码不会从1&gt; 120开始,因为您在8次迭代后将其分解。 要从基础120获得值15 30 45 60 75 90 105 120,您需要这样的东西:
$result = array();
$duration = 120; //the duration in seconds as provided in the example
$divider = 8; //the divider 8 as provided by the example
for ($i = 1; $i <= $divider; $i++) {
//This will give 1* 120/8 = 15 for the first run
//2* 120/8 = 30 for the second and so on
$result[] = (int) $i * $duration / $divider;
}