3 回答

TA貢獻(xiàn)1847條經(jīng)驗 獲得超7個贊
您可以通過運行 for 循環(huán)來簡單地做到這一點。創(chuàng)建一個包含一系列元素的數(shù)組并運行 for 循環(huán)。雖然您將在那個時間運行循環(huán),但根據(jù)給定的三組計算數(shù)組元素。最后,您將獲得給定范圍內(nèi)的元素總數(shù)。為了您在下面獲得更好的幫助,我舉了一個例子:
<?php
$number = array(80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110);
$count1 = $count2 = $count3 = 0;
for ($i = 0; $i < sizeof($number); $i++) {
if($number[$i] >= 80 && $number[$i] <= 90 ) {
$count1++;
}
if($number[$i] >= 90 && $number[$i] <= 100 ) {
$count2++;
}
if($number[$i] >= 100 && $number[$i] <= 110 ) {
$count3++;
}
}
echo "The number between 80-90 = ".$count1."<br>";
echo "The number between 90-100 = ".$count2."<br>";
echo "The number between 100-110 = ".$count3."<br>";
?>

TA貢獻(xiàn)1811條經(jīng)驗 獲得超4個贊
為避免在您確定號碼所屬的位置時進(jìn)行太多比較,跳轉(zhuǎn)到下一個循環(huán)。
function countOccurences( array $numbersArray ):array
{
$return = array('n80to90' => 0, 'n90to100' => 0, 'n100to110' => 0);
foreach( $numbersArray as $number ){
if( $number < 80 || $number > 110 )
continue;
if($number < 91){
$return['n80to90']++;
continue;
}
if($number < 101){
$return['n90to100']++;
continue;
}
$return['n100to110']++;
}
return $return;
}

TA貢獻(xiàn)1853條經(jīng)驗 獲得超9個贊
我認(rèn)為 OP 可能會尋求更Pythonic 的答案(但在 PHP 中)
//only valid in php 5.3 or higher
function countInRange($numbers,$lowest,$highest){
//bounds are included, for this example
return count(array_filter($numbers,function($number) use ($lowest,$highest){
return ($lowest<=$number && $number <=$highest);
}));
}
$numbers = [1,1,1,1,2,3,-5,-8,-9,10,11,12];
echo countInRange($numbers,1,3); // echoes 6
echo countInRange($numbers,-7,3); // echoes 7
echo countInRange($numbers,19,20); //echoes 0
'use' 關(guān)鍵字表示 php 中的'關(guān)閉'。在其他語言中,例如javascript,當(dāng)然,外部函數(shù)中的變量會自動按范圍導(dǎo)入到內(nèi)部函數(shù)中(即沒有特殊關(guān)鍵字),內(nèi)部函數(shù)也可以稱為“部分函數(shù)”。
由于某些原因,在 PHP 5.2x 或更低版本中,變量不會自動按范圍導(dǎo)入,而在 PHP 5.3 或更高版本中,use 關(guān)鍵字可以克服這個問題。語法非常簡單:
$functionHandle = function(<arguments>) use (<scope-imported variables>){
//...your code here...
}
- 3 回答
- 0 關(guān)注
- 281 瀏覽
添加回答
舉報