【问题标题】:PHP words array countPHP 单词数组计数
【发布时间】:2013-01-14 15:04:06
【问题描述】:

我的数组是

$myarray=array("人类","天使",上帝"","天使","恶魔","上帝","上帝","人类","上帝","天使");

如何获取单词并像计数一样

God : 4
Angel : 3
Human : 2
Devil : 1

【问题讨论】:

  • 你有没有尝试过?
  • 这是一个“阅读文档”问题。

标签: php arrays


【解决方案1】:

您可以使用array-count-values 函数。

【讨论】:

    【解决方案2】:

    array_count_values

    来自文档:

    Example #1 array_count_values() example
    <?php
      $array = array(1, "hello", 1, "world", "hello");
      print_r(array_count_values($array));
    ?> 
    
    Array
    (
      [1] => 2
      [hello] => 2
      [world] => 1
    )
    

    【讨论】:

      【解决方案3】:

      看看array_count_valuesarsort

      <?php  
      $myarray = array("Human","Angel","God","Angel","Devil","God","God","Human","God","Angel");
      
      $result = array_count_values($myarray);
      arsort($result);
      
      foreach($result as $word => $count)
      {
          echo $word." was found ".$count." time(s)<br/>";
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-11
        • 2013-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-26
        • 1970-01-01
        相关资源
        最近更新 更多