简体   繁体   English

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

[英]Laravel: get the most used words with eloquent

I have a table post and it have a column content. 我有一个表发布,它有一个列内容。 The content column is text. 内容列是文本。 I want to get the most used words in content today with eloquent 我想雄辩地获得内容中最常用的单词

Try this, assuming table name = post and field name = content : 尝试此操作,假设表名= post和字段名= content

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

Will get the first most common content in the table, and: 会得到第一个最常用的content表中,并且:

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

Will get the registers ordered from the most common to the most rare. 将按从最常见到最稀有的顺序获得寄存器。 By the way, this is just an adaption from MySQL to Eloquent according to this example 顺便说一下,根据这个例子 ,这只是从MySQL到Eloquent的改编

I think what you are looking for is this. 我认为您正在寻找的是这个。

NOTE : since you have not provided any table structure, I don't know how to filter today's posts. 注意 :由于您还没有提供任何表结构,因此我不知道如何过滤今天的帖子。 I hope there is a column named date . 我希望有一列名为date的列。

Count all the words that has used today. 数数今天使用的所有单词。

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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