Laravel:雄辩地得到最常用的单词

时间:2018-10-04 19:58:53

标签: php mysql laravel

我有一个表帖子,它有一个列内容。内容列是文本。今天,我想雄辩地获得内容中最常用的单词

2 个答案:

答案 0 :(得分:2)

尝试此操作,假设表名称= post,字段名称= content

$mostUsed = Post::take(1)
    ->groupBy('content')
    ->orderBy('content', 'desc')
    ->count('content');

将在表格中获得第一最常见的content,并且:

$mostUsed = Post::groupBy('content')
    ->orderBy('content', 'desc')
    ->count('content');

将使寄存器从最常见到最稀有排序。顺便说一下,根据this example

,这只是从MySQL到Eloquent的改编

答案 1 :(得分:1)

我认为您正在寻找的是这个。

注意:由于您未提供任何表格结构,因此我不知道如何过滤今天的帖子。我希望有一个名为date的列。

计算今天使用的所有单词。

// array of all the content strings.
$contents = Post::where('date', date('Y-m-d'))->pluck('content');

// final result will be stored here as a key value pair.
// used count against each word.
$word_count = [];

foreach($contents as $content) {

    // array of each word in the content separated by 'space'.
    $words = explode(' ', $content);

    foreach($words as $word) {

        // if the word has already used +1 the count, else set the count as 1.
        $count = array_key_exists($word, $word_count) ? ($word_count[$word] + 1) : 1;

        // set new word count to the array.
        array_set($word_count, $word, $count);
    }
}

$most_used_word = array_search(max($word_count), $word_count);