PHP: Counting the number of occurrences of each word in an associative array of Strings

时间:2017-04-10 03:31:05

标签: php mysql arrays string search

let the array be as

{
element [0] = 'Mary',
element [1] = 'Mary had a little',
element [2] = 'a lamb',
element [3] = 'Mary mary mary',
.
.
element [n] = 'lady'
}

Output:

Mary : 5
a : 2
had : 1
little : 1
lady : 1

2 个答案:

答案 0 :(得分:3)

PHP code demo

<?php
$array=array(
0 => 'Mary',
1 => 'Mary had a little',
2 => 'a lamb',
3 => 'Mary mary mary',
4 => 'lady'
);
$data=array();
foreach($array as $sentence)
{
    //gatering words in an array by spliting the sentence on space.
    $data=  array_merge($data,explode(" ", $sentence));
}
//counting values present in array for case sensitive
$result=array_count_values($data);
print_r($result); //Result 1

//counting values present in array for case insensitive by changing each array element to lowercase
$result=array_count_values(array_map("strtolower", $data));
print_r($result); //Result 2

<强>输出:

//result 1
Array
(
    [Mary] => 3
    [had] => 1
    [a] => 2
    [little] => 1
    [lamb] => 1
    [mary] => 2
    [lady] => 1
)
//result 2
Array
(
    [mary] => 5
    [had] => 1
    [a] => 2
    [little] => 1
    [lamb] => 1
    [lady] => 1
)

答案 1 :(得分:0)

进行explode()array_merge()的迭代调用效率很低。只需让implode()将数据压缩为字符串,减少大小写,转换回一维数组,然后计数即可。容易。

代码:(Demo

$array = [
    'Mary',
    'Mary had a little',
    'a lamb',
    'Mary mary mary',
    'lady'
];

var_export(
    array_count_values(
        explode(' ',
            strtolower(
               implode(' ', $array)
            )
        )
    )
);

输出:

array (
  'mary' => 5,
  'had' => 1,
  'a' => 2,
  'little' => 1,
  'lamb' => 1,
  'lady' => 1,
)