计算另一个数组中一个数组的单词出现次数

时间:2015-08-06 15:08:50

标签: php

我有两个数组:$story$languages

现在我想知道$languages数组中$story中出现的元素或值的次数。这意味着多少次" php"," javascript"," mysql" $languages数组中出现了$story数组?

我怎么能在PHP中这样做?有人可以帮忙吗?这是我的阵列......

$story = array();
$story[] = 'As a developer, I want to refactor the PHP & javascript so that it has less duplication';
$story[] = ' As a developer, I want to configure Jenkins so that we have continuous integration and I love mysql';
$story[] = ' As a tester, I want the test cases defined so I can test the system using php language and phpunit framework';

$languages = array(
  'php', 'javascript', 'mysql'  
);

3 个答案:

答案 0 :(得分:2)

我会将总计存储在$languages数组中。在添加之前无需检查计数,因为添加0不会影响您的总计。

<?
    $story = array();
    $story[] = 'As a developer, I want to refactor the PHP & javascript so that it has less duplication';
    $story[] = ' As a developer, I want to configure Jenkins so that we have continuous integration and I love mysql';
    $story[] = ' As a tester, I want the test cases defined so I can test the system using php language and phpunit framework';

    $languages = array(
        'php' => 0,
        'javascript' => 0,
        'mysql' => 0
    );

    foreach ($story as $sk => $sv){
        foreach ($languages as $lk => $lv){
            $languages[$lk] += substr_count($story[$sk], $lk);
        }
    }

    print_r($languages);
?>

答案 1 :(得分:1)

有2个循环: https://ideone.com/grRBeG

$story = array();
$story[] = 'As a developer, I want to refactor the PHP & javascript so that it has less duplication';
$story[] = ' As a developer, I want to configure Jenkins so that we have continuous integration and I love mysql';
$story[] = ' As a tester, I want the test cases defined so I can test the system using php language and phpunit framework';

$languages = [
    'php' => 0,
    'javascript' => 0,
    'mysql' => 0,
];

for( $i=0,$size=count($story); $i<$size; ++$i )
{
    $text = strtolower($story[$i]);
    foreach( $languages as $word => $nb )
        $languages[$word] += substr_count($text, $word);
}

var_export($languages);

答案 2 :(得分:0)

运行两个foreach循环,如下所示。

$finalCount = array();
foreach($story as $current)
{
      $count=0;
     foreach($languages as $language){
         if (substr_count($current,$language) !== false) {
           $count++
         }
     }
     $finalCount[$language] = $count;

}