【发布时间】:2021-09-15 15:22:03
【问题描述】:
我有一个包含多个数字的数组。 我想要做的是得到一个循环并运行到这个数组中并计算我有多少个两位数,三位数,四位数。
我尝试过的:
$myArray = array(123,1234,12345,123456,123567);
for($i=1,$size=count($myArray);$i<=$size;i++)
{
if(strlen($i==3)) echo "the number with index " .$i. " is three-digit number.";
else if(strlen($i==4)) echo "the number with index " .$i. " is four-digit number.";
...
}
我也试过这个:
$threeDigits=0;
$fourDigits=0;
$fiveDigits=0;
$sixDigits=0;
$myArray=(123,1234,12345,123456,1234567,111,222)
for($i=1,$size=count($myArray);$i<=$size;i++)
{
if(strlen($==3)) $threeDigits++;
else if(strlen($i==4)) $fourDigits++;
else if(strlen($i==5)) $fiveDigits++;
else if(strlen($i==6)) $sixDigits++;
}
echo "There are " .$fourDigits. " numbers with 4 digits.";
echo "There are " .$threeDigits. " numbers with 3 digits.";
echo "There are " .$fiveDigits. " numbers with 5 digits.";
echo "There are " .$sixDigits. " numbers with 6 digits.";
但不知何故,它只将它们视为一个。如您所见,在我的数组中有三个三位数,但是当我打印出来时,它说我只有一个。您认为这可能是什么问题?
【问题讨论】:
-
我不确定所涉及的指标,但可能先对数组进行排序?
-
排序在这里有什么帮助?
-
定义“最佳”...您对当前解决方案的哪些方面不满意?除非您能描述问题和/或更具体的目标,否则很难提出改进建议
-
提示:使用
foreach->foreach(myArray as key, value)或只使用foreach(myArray as value),遍历数组更简单 -
近骗:stackoverflow.com/a/1762216/2943403;我会努力寻找更好的