【问题标题】:How to count the number of certain string inside array?如何计算数组中某个字符串的数量?
【发布时间】:2011-08-28 10:15:53
【问题描述】:

嘿! 我正在尝试计算某个字符串存在于数组中的次数。这个我试过了。。 我的数组:

$test = array('correct','correct','incorrect','incorrect','correct');

in_array('correct',$test); // only gives me true

我想到了 count();但这只会返回项目的数量......那么如何计算该数组中有多少“正确”的字符串?

谢谢!

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    使用preg_grep 怎么样?

    $count = count(preg_grep('/^correct$/', $test));
    

    【讨论】:

      【解决方案2】:

      怎么样:

      $count = 0;
      foreach($test as $t)
          if ( strcmp($t, "correct") == 0)
               $count++;
      

      【讨论】:

      【解决方案3】:

      为此,我将countarray_filter 结合起来:

      $count = count(array_filter($test, function($val) {
          return $val === 'correct';
      }));
      

      请注意,函数语法仅支持 PHP >=5.3。

      【讨论】:

        【解决方案4】:
        $count = 0;
        
        foreach ($test as $testvalue) {
        if ($testvalue == "correct") { $count++; }
        }
        

        【讨论】:

          【解决方案5】:
          function count_instances($haystack, $needle){
            $count = 0;
            foreach($haystack as $i)
              if($needle == $i)
                $count++;
            return $count;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-02-24
            • 1970-01-01
            • 2013-12-25
            • 2016-05-24
            • 2017-10-09
            • 2010-11-12
            相关资源
            最近更新 更多