简体   繁体   中英

PHP how to display the 5 most reccurent words in a list

我有一个列表,其中存储了访问过的网站(一千),我需要显示前5个访问最多的网站:

$websites= "site#1.com site#2.com site#1.com site#1.com site#3.com ... "

That's a string, so you have to convert it into an array:

$websites_array = explode(" ", $websites);

then you can get element frequencies with

$frequencies=array_count_values($websites_array)
$most_frequent_websites=array_keys($frequencies, max($frequencies))

the array_count_values returns a frequency map, array_keys find the key (website) associated to the maximum value.

Note that in case you have more than one website with the highest count, it will return an array of most frequent websites.

try this

$sites = explode(' ',$site_string);
$top5 = array_count_values($array);
rsort($top5);
$top5 = array_slice($top5, 0, 5);

Easiest solution:

$websites= "site#1.com site#2.com site#1.com site#1.com site#3.com site#2.com";
$sites = explode(' ', $websites);
foreach($sites as $site)
    $visits[$site]++;

// Sort by descending number of visits
arsort($visits);  
var_dump($visits);

Working sample .

This is deliberately verbose so you understand what's going on:

<?php

$websites = "site#1.com site#2.com site#1.com site#1.com site#3.com";

//presuming they'll always be seperated by a single space...
$sites = explode(' ', $websites);

$siteCount = array();

foreach ($sites as $site) {
  if (!isset($siteCount[$site])) {
    $siteCount[$site] = 1;
  } else {
    $siteCount[$site]++;
  }
}

arsort($siteCount);

$finalArray = array_slice($siteCount, 0, 5);

var_dump($siteCount);

Which outputs:

array(3) {
  ["site#1.com"]=&gt;
  int(3)
  ["site#3.com"]=&gt;
  int(1)
  ["site#2.com"]=&gt;
  int(1)
}

We could do this that way :

$websites_array = explode(' ', $websites);

$top_websites = array_count_values($websites_array);

asort($top_websites);

// $top_websites = array('#site2' => 5, '#site4' => 4, '#site1' => 2, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM