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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jclarkkent2003
Forum Contributor
Posts: 123
Joined: Sat Dec 04, 2004 9:14 pm

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

Post 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? :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

jclarkkent2003
Forum Contributor
Posts: 123
Joined: Sat Dec 04, 2004 9:14 pm

Post 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";

}

?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

foreach :?
Please use

Code: Select all

tags for php code.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

asort
jclarkkent2003
Forum Contributor
Posts: 123
Joined: Sat Dec 04, 2004 9:14 pm

Post by jclarkkent2003 »

Code: Select all

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