我想计算String变量中的重复单词

时间:2017-11-05 20:50:43

标签: php

我想计算重复单词并显示

Fruits

如何显示 abc = 4 aec = 3 ..

2 个答案:

答案 0 :(得分:1)

<?php
$string = "abc, abcd, aec, abc, aaa, ccc, aec, abc, efg, abc, aaa, aec, cde";

$words = explode(',',$string);
$results = array();

foreach($words as $key) {
    if(!isset($results[$key])){
        $results[$key] = 0;
    }

    $results[$key]++;
}

var_dump($results);

接缝为我工作:)

答案 1 :(得分:1)

我使用array_reduce而不是foreach循环:

$string = "abc, abcd, aec, abc, aaa, ccc, aec, abc, efg, abc, aaa, aec, cde";

$array = explode(',', $string);

//Trim it up first.
$array = array_map(function($item){
    return trim($item);
}, $array);

$array = array_reduce($array, function($carry, $item){
    if(isset($carry[$item])) {
        $carry[$item]++;
    } else {
        $carry[$item] = 1;
    }

    return $carry;
});

var_dump($array);

Try it!