多个计数器不计(foreach / ifs)

时间:2014-07-14 21:51:36

标签: php if-statement for-loop counter

这是我的第一篇StackOverFlow帖子。

我有一系列数字,我随便洗牌:

$nums = array("1","1","1","1","1","2","2","2","2","3","3","3","4","4","4");
shuffle($nums);
  1. 我正在尝试识别洗牌数组中连续三个3个相同数字的序列/模式
  2. 输出所有匹配数字组合的总和。
  3. 我遇到的问题似乎源于试图将循环中的当前数字与之前的数字进行比较(以查看它们是否匹配)。

    当我回应"之前"数字总是输出为" 0"。因此,我无法比较当前数字和旧数字,这意味着我无法对相同数字的模式进行求和并求和。

    这是我的代码:

    <?php
    $t3count = 0;
    $oldnum = 0;
    $tots = 0;
    $nums = array("1","1","1","1","1","2","2","2","2","3","3","3","4","4","4");
    shuffle($nums);
    foreach ($nums as $num) {
      echo "$num: [$oldnum] ";
        if ($num = $oldnum) {
          $t3count++;
            if ($t3count = 3) {
              $tots = $num * $num;
              $t3count = 0;
              $oldnum = $num;
            } else {
              # do nonum
            }
          } 
          else {
           $oldnum = $num; 
          }
          # echo "<li>$num</li>";    
       }
    
     echo "Your total is: $tots";
     unset($num);
    

    &GT;

    谢谢。

3 个答案:

答案 0 :(得分:1)

您需要在此处进行比较==而非作业=

if ($num = $oldnum)

在这里:

if ($t3count = 3)

答案 1 :(得分:0)

如果我的逻辑正确

,这也许会让你感到害怕
 $t3count++;
 if ($t3count == 3) {

你怎么知道哪一个计算到3,id先构建类似值的嵌套数组然后处理它。

答案 2 :(得分:0)

你错过了==比较if($ num = $ oldnum)和if($ t3count = 3)

替换为

if($ num == $ oldnum)

if($ t3count == 3)