【问题标题】:php count words in array of variablesphp计算变量数组中的单词
【发布时间】:2015-01-27 05:27:36
【问题描述】:

我有一个可变字符串数组,我想计算所有逗号并找到所有字符串中的总逗号。我知道我必须使用 explode 和 foreach 但不知道如何将它们放在一起以及如何在末尾添加所有逗号...

 $log1 = "one, two, three,";

 $log2 = "red, blye, green,";

 $log3 = "sunny day, snowy day, nice one,";

 $main_log = array(log1, log2, log3);

【问题讨论】:

  • 你希望最终结果如何?你期望$main_log 是什么?
  • 只是一个数字作为变量,如 $main_log 在上面的例子中是 9
  • blye 颜色是什么? :)
  • 加上会有语法错误....应该是$main_log=array($log1, $log2, $log3)

标签: php arrays foreach


【解决方案1】:

请进行一些更正。将所有字符串连接起来,而不是像下面的代码那样将它们推入一个数组;

$log1 = "one, two, three,";

 $log2 = "red, blye, green,";

 $log3 = "sunny day, snowy day, nice one,";

 $main_log = $log1.$log2.$log3;
 echo substr_count($main_log, ','); //prints 9

【讨论】:

    【解决方案2】:

    你想数逗号 - 就这么做吧:

    array_sum(array_map(function($str){
      return substr_count($str, ',');
    }, $main_log));
    

    【讨论】:

      【解决方案3】:

      像这样修改你的代码 -

      $log1 = "one, two, three";
      $log2 = "red, blye, green";
      $log3 = "sunny day, snowy day, nice one";
      
      $arr1 = explode(',', $log1);
      $arr2 = explode(',', $log2);
      $arr3 = explode(',', $log3);
      
      
      $main_log = array_merge($arr1,$arr2,$arr3);   //Array merge
      $count = array_count_values($main_log); //Total count the array values
      

      【讨论】:

        【解决方案4】:

        这里还有另外几个解决方案:

        $log1 = "one, two, three,";
        $log2 = "red, blye, green,";
        $log3 = "sunny day, snowy day, nice one,";
        
        $main_log = $log1.$log2.$log3;
        
        echo count(explode(',',$main_log))-1;
        
        echo substr_count($main_log, ',');
        

        【讨论】:

          【解决方案5】:
          substr_count($string, ',');
          

          对于数组.... @vp_arth 的解决方案会起作用...

          $log1 = "one, two, three,";
          
          $log2 = "red, blye, green,";
          
          $log3 = "sunny day, snowy day, nice one,";
          
          $main_log = array($log1, $log2, $log3);
          
          $result= array_sum(array_map(function($str){
            return substr_count($str, ',');
          }, $main_log));
          
          
          echo $result;
          

          【讨论】:

          • substr_count() 仅适用于字符串。 $main_log 是一个数组
          猜你喜欢
          • 2023-04-11
          • 1970-01-01
          • 2013-01-14
          • 1970-01-01
          • 1970-01-01
          • 2013-06-14
          • 2017-11-08
          • 2015-03-01
          • 1970-01-01
          相关资源
          最近更新 更多