Page 1 of 1

Best way to sort and add mulitple occurences of a variable..

Posted: Mon Feb 13, 2006 10:33 pm
by jclarkkent2003
Hi guys,
What's the best way to COUNT and SORT multiple values of an array.

Example:

Timeless
Links
Timeless
Orangles
Kiwis
Apples
Timeless
Link
Bannana
Apples



I need to get THIS in the end result:

4 Timless
2 Apples
1 Links
1 Orangles
1 Kiwis
1 Link
1 Bannana

I know about array_keys() with the search thingy will return how many times a variable occurs in an array, but how would I add up EXACT matches, then RESORT based on MAXIMUM occurances of that word/variable all the way down to least occurances? And I need to REMOVE duplicates array_unique() I think will work, but I need to have the number times it was in the array as well....

Any bright ideas? :)

Posted: Mon Feb 13, 2006 10:46 pm
by feyd

Posted: Mon Feb 13, 2006 11:04 pm
by jclarkkent2003
ok, ksort, sorts by keys, which means it will abc order the WORDS, and I need it to sort by DESCENDING VALUES since the number of times the variable occurs is in the value slot.

then how do I echo or manipulate this to my likings?

Code: Select all

<?
$test = array("Timeless",
"Links",
"Timeless",
"Orangles",
"Kiwis",
"Apples",
"Timeless",
"Link",
"Bannana",
"Apples");


$test2 = array_count_values($test);

arsort($test2);
print_r($test2);

// WORKS UP TO THERE, but how do I echo or set that information equal to something? The next for loop is how I USUALLY traverse an array for information but doesn't work.

for($k=0;$k<sizeof($test2);$k++)
{
	echo "$k = $test2[$k] <br>\n";

}

?>

Posted: Mon Feb 13, 2006 11:25 pm
by feyd
foreach :?
Please use

Code: Select all

tags for php code.

Posted: Mon Feb 13, 2006 11:25 pm
by josh
asort

Posted: Mon Feb 13, 2006 11:32 pm
by jclarkkent2003

Code: Select all

foreach ($test2 as $key => $value) {
   echo "Key: $key; Value: $value<br />\n";
}
Bingo, thanks that works!