0

我是新手PHP,一般来说,我对如何计算特定数字在数组中出现的次数非常迷茫。

例如,我需要计算2数组中出现的次数。

然后我需要将该值传输到另一个变量才能输出它。

我已经尝试过array_count_value,但似乎无法将其输出。

这是我的数组,我需要计算每个数字出现的次数。

我已经尝试过 if 语句,我已经尝试了所有我读过的东西,但没有任何效果,我得到的只是一个空白屏幕。

for($counter=0; $counter <=999; $counter++)
{
$die=rand(2,12);
$int[$counter]=$die;
echo "$int[$counter],";
}
4

2 回答 2

0

尝试这个:

$rolls = array();

for($x=2;$x<12;$x++)
{
    $rolls[$x]=0;
}

for($counter=0; $counter <=999; $counter++)
{
    $rolls[rand(2,12)]++;
}

然后检索数字滚动的次数:

echo $rolls[2];

这将输出数字 2 的滚动次数。

于 2013-08-10T02:06:24.833 回答
0

您可以使用这样的计数器:

$total = 0;
for($counter=0; $counter <=999; $counter++)
{
  $die=rand(2,12);
  if($die == 2){
    $total ++; //if its two add 1 to total.
  }
  $int[$counter]=$die;
}

echo 'Total times 2 appeared '. $total;

或者如果你想专门计算一个数组:

for($counter=0; $counter <=999; $counter++)
{
  $die=rand(2,12);
  $int[$counter]=$die;
}
$total = array_count_values($int);
$total_for_two = $total[2];
echo 'Total times 2 appeared '.$total_for_two
于 2013-08-10T01:52:32.393 回答