在php中计算数组中的相同字符串

时间:2018-04-09 05:49:49

标签: php

我有一个包含相同字符串值的数组,我如何将这些相同的字符串计算为数字。

示例数组:

$animals = array('dog','dog','cat','mouse','cat');

输出:

dog x2,
cat x2,
mouse x1

4 个答案:

答案 0 :(得分:1)

使用array_count_values

$animals = array('dog','dog','cat','mouse','cat');
$count_values = array_count_values($animals);

print_r($count_values );

输出

Array
(
    [dog] => 2
    [cat] => 2
    [mouse] => 1
)

并像这样迭代它

foreach($occurences as $key => $item){
    echo $key ." x" .$item .",";
    print "\n";
}

答案 1 :(得分:1)

这样做:

// The verbose way
<?php
   $counts = [];
   $animals = array('dog','dog','cat','mouse','cat');

   foreach ($animals as $value) {
       if (key_exists($value, $counts)) {
           $counts[$value] += 1;
       } else {
           $counts[$value] = 1;
       }
   }
?>

...但是php有一个完全符合

的方法
<?php
    $counts = array_count_values($animals);
?>

以后,如果要打印出现

foreach ($counts as $key => $value) {
    echo $key." x".$value."<br />";
}

答案 2 :(得分:1)

您需要foreach()使用array_count_values()这样的

$animals = array('dog','dog','cat','mouse','cat');
$values=array_count_values($animals) ;
foreach ($values as $key=>$value) {
    echo $key ."X". $value;
    echo '<br>';
}

答案 3 :(得分:0)

<?php 
$array =  array('dog','dog','cat','mouse','cat');
$vals = array_count_values($array);
// print_r($vals);
foreach ($vals as $key=>$value) {
  echo $key ." X". $value;
  echo '<br>';
}
?>