简体   繁体   中英

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 :

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

Will get the first most common content in the table, and:

$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

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 .

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

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