How to sort array decreasingly?

Asked

Viewed 244 times

3

I have the following problem, after making a array `push, I want to return the amount of repetition of a term for this:

$key = str_replace(array(',','.','https','/','#','!','@','&','?','\\',':','\'','”','(',')', 'ª','º','1','2','3','4','5','6','7','8','9','0','“','"','','','','-','','','❤','','','','','k','','',''), ' ', strtolower($key));           

$wreply = split(' ',$key);

foreach ($wreply as $wkr) 
{
     if (strlen($wkr) > 3) {array_push($words, $wkr);}
} 

$contagem = array_count_values($words);

this code gives me the word and the amount that was repeated

Example:

a => 5

I want to order it by its value, I used the rsort thus:

$sort   = rsort($contagem);

foreach ($sort as $key => $value) 
{
    echo "$key => $value,";
}  

2 answers

2

Two things:

  1. The rsort reorders the original array itself, and does not return a new one (returns true or false indicating whether or not the operation was successful).

  2. The rsort throw away the keys from the original array, and you seem to want to keep the keys. This you solve using arsort.

Therefore:

arsort($contagem); // reordena in-place como o rsort, mas mantendo as chaves
foreach ($contagem as $key => $value) 
{
    echo "$key => $value,";
}  

2


Uses the array_count_values() along with the arsort().

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
    'pear', 'kiwi', 'kiwi', 'kiwi');

$output = array_count_values($array);
arsort($output);

print_r($output);

Exit

Array
(
    [kiwi] => 3
    [apple] => 2
    [pear] => 2
    [orange] => 1
    [banana] => 1
)

Note: I used a reply as a reference of ONLY and adapted to your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.