Order Items of an Array by quanity?

  • RedBMedia
  • Proficient
  • Proficient
  • User avatar
  • Joined: May 01, 2007
  • Posts: 315
  • Status: Offline

Post October 12th, 2011, 8:49 am

Lets say I have an array like so:

Code: [ Select ]
Array
(
[0] => apple
[1] => pear
[2] => apple
[3] => orange
[4] => pear
[5] => apple
)
  1. Array
  2. (
  3. [0] => apple
  4. [1] => pear
  5. [2] => apple
  6. [3] => orange
  7. [4] => pear
  8. [5] => apple
  9. )


And I want to print it like so:

apple - 3
pear - 2
orange - 1

How would one do that? Do I need to loop twice, once to count the items, and then once to organize and print with numbers?
Joe Hall
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post October 12th, 2011, 8:49 am

  • RedBMedia
  • Proficient
  • Proficient
  • User avatar
  • Joined: May 01, 2007
  • Posts: 315
  • Status: Offline

Post October 12th, 2011, 8:53 am

Oh and as a side note, I am talking about PHP here, sorry! :)
Joe Hall
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Joined: Dec 20, 2002
  • Posts: 8926
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Post October 12th, 2011, 9:40 am

I could be wrong, but I think that is exactly how I would do it for that situation. I am not aware of anyway to do what you want with a single sort or single loop through. This function:

array_count_values

might be useful for you though, it does count all of the values in the array. So you might be able to run that function first, then do a sort on the array.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Joined: Sep 22, 2003
  • Posts: 6130
  • Loc: Seattle, WA
  • Status: Offline

Post October 12th, 2011, 10:06 am

array_count_values() is exactly what you want. Since the output is a hash, it's technically already sorted.
The Beer Monocle. Classy.

Post Information

  • Total Posts in this topic: 4 posts
  • Users browsing this forum: No registered users and 124 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.