Sort array by repeated words in PHP

0

I have an array in PHP (laravel) with words extracted from certain tweets. I need to be able to create a list or table where a word is displayed and the number of times it repeats in that array. That is, if the word is "hello" and it is repeated 6 times, the word appears and the number of times it repeats. Only that.

    
asked by Joaquin Perea 16.12.2018 в 22:53
source

2 answers

0

I do not know if it's the most efficient way to do it but I would do it with a function like this:

function palabras($str) {
$palabras = explode(" ", $str);
$palabrasArray = [];
$contador = [];
foreach($palabras as $palabra) {
  if(in_array($palabra, $palabrasArray)) {
    array_push($palabrasArray, $palabra);
    $contador[$palabra]++;
  } else {
    array_push($palabrasArray, $palabra);
    $contador[$palabra] = 1;
  }
}
arsort($contador);
return $contador;
  }
  $string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

  palabras($string);

I forgot that it's laravel, simply believe the same but in one method

public function contarPalabras($str) {
  ...
}

And you call it that:

$this->contarPalabras($cadenaOTweet);
    
answered by 17.12.2018 в 00:32
0

PHP has many functions to handle arrays that greatly facilitate any work, I leave you an alternative:

//palabras a contar
$words=['hola','adios'];

//frase a usar para contar palabras
$frase='hola gato, hola perro, hola sol, adios nube, adios';

//eliminamos cualquier caracter que no sea una letra
$frase=preg_replace("/[^A-Za-z ]/", '', $frase);

//array_count_values hace el trabajo facil resumiendo el total
//de apariciones por cada elemento de un array .   
$w=array_count_values(explode(' ',$frase));

var_export($w);

Posting result

array ( 'hola' => 3, 'gato' => 1, 'perro' => 1, 'sol' => 1, 'adios' => 2, 'nube' => 1 )

Filter words that interest me to search

//y finalmente nos quedamos con la interseccion de ambos arrays    
$matches = array_intersect_key($w, array_flip($words));

var_export($matches);

Result

array ( 'hola' => 3, 'adios' => 2 )

Function and usage example

function contarPalabra($frase,$filtro){
    $w=array_count_values(explode(' ',preg_replace("/[^A-Za-z ]/", '', $frase)));
    return array_intersect_key($w, array_flip($filtro));
}

$frase='hola gato, hola perro, hola sol, adios nube, adios';

$cuenta = contarPalabra( $frase, ['gato']);

var_export($cuenta);

Testing

$words=['hola','adios'];
$frase='hola gato, hola perro, hola sol, adios nube, adios';

echo '<hr>';
$cuenta = contarPalabra( $frase, ['hola']);
var_export($cuenta);

echo '<hr>';
$cuenta = contarPalabra( $frase, ['perro']);
var_export($cuenta);

echo '<hr>';
$cuenta = contarPalabra( $frase, ['adios']);
var_export($cuenta);

Resumodos

array ( 'hola' => 3, )
array ( 'perro' => 1, )
array ( 'adios' => 2, )

On the PHP.net site you can find all the functions and definitions for managing arrays. link

    
answered by 17.12.2018 в 05:44