PHP - 计算特定范围内的数组元素

我有一个包含 950 个元素的数组。元素的值在 80-110 之间。我想在 80-90、90-100 和 100-110 之间数一数。然后我会在图表上显示它们。这可以计算 php 中的元素吗?


胡说叔叔
浏览 255回答 3
3回答

aluckdog

您可以通过运行 for 循环来简单地做到这一点。创建一个包含一系列元素的数组并运行 for 循环。虽然您将在那个时间运行循环,但根据给定的三组计算数组元素。最后,您将获得给定范围内的元素总数。为了您在下面获得更好的帮助,我举了一个例子:<?php&nbsp; &nbsp; $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);&nbsp; &nbsp;$count1 = $count2 = $count3 = 0;&nbsp; &nbsp;for ($i = 0; $i < sizeof($number); $i++) {&nbsp; &nbsp; &nbsp; &nbsp;if($number[$i] >= 80 && $number[$i] <= 90 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$count1++;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;if($number[$i] >= 90 && $number[$i] <= 100 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$count2++;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;if($number[$i] >= 100 && $number[$i] <= 110 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$count3++;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}&nbsp; &nbsp;echo "The number between 80-90 = ".$count1."<br>";&nbsp; &nbsp;echo "The number between 90-100 = ".$count2."<br>";&nbsp; &nbsp;echo "The number between 100-110 = ".$count3."<br>";?>

波斯汪

为避免在您确定号码所属的位置时进行太多比较,跳转到下一个循环。function countOccurences( array $numbersArray ):array{&nbsp; $return = array('n80to90' => 0, 'n90to100' => 0, 'n100to110' => 0);&nbsp; foreach( $numbersArray as $number ){&nbsp; &nbsp; if( $number < 80 || $number > 110 )&nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; if($number < 91){&nbsp; &nbsp; &nbsp; $return['n80to90']++;&nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; if($number < 101){&nbsp; &nbsp; &nbsp; $return['n90to100']++;&nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; $return['n100to110']++;&nbsp; }&nbsp;&nbsp; return&nbsp; $return;}

暮色呼如

我认为 OP 可能会寻求更Pythonic 的答案(但在 PHP 中)//only valid in php 5.3 or higherfunction countInRange($numbers,$lowest,$highest){&nbsp; //bounds are included, for this example&nbsp; &nbsp; &nbsp; return count(array_filter($numbers,function($number) use ($lowest,$highest){&nbsp; &nbsp; return ($lowest<=$number && $number <=$highest);&nbsp;&nbsp; &nbsp; }));}$numbers = [1,1,1,1,2,3,-5,-8,-9,10,11,12];echo countInRange($numbers,1,3); // echoes 6echo countInRange($numbers,-7,3); // echoes 7echo countInRange($numbers,19,20); //echoes 0'use' 关键字表示 php 中的'关闭'。在其他语言中,例如javascript,当然,外部函数中的变量会自动按范围导入到内部函数中(即没有特殊关键字),内部函数也可以称为“部分函数”。由于某些原因,在 PHP 5.2x 或更低版本中,变量不会自动按范围导入,而在 PHP 5.3 或更高版本中,use 关键字可以克服这个问题。语法非常简单:$functionHandle = function(<arguments>) use (<scope-imported variables>){&nbsp; &nbsp; //...your code here...}
打开App,查看更多内容
随时随地看视频慕课网APP