Order Items of an Array by quanity?

  • RedBMedia
  • Proficient
  • Proficient
  • User avatar
  • Posts: 315

Post 3+ Months Ago

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?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • RedBMedia
  • Proficient
  • Proficient
  • User avatar
  • Posts: 315

Post 3+ Months Ago

Oh and as a side note, I am talking about PHP here, sorry! :)
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9086
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

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.
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6243
  • Loc: Seattle, WA

Post 3+ Months Ago

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

Post Information

  • Total Posts in this topic: 4 posts
  • Users browsing this forum: No registered users and 66 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
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.