0

I have an array that sometimes has duplicate entries, say I have an array

array("dog", "cat", "cat", "mouse", "cat", "dog")

Now if I used the method I found here I can make the array a unique array like this

array("dog", "cat", "mouse")

However what I am trying to do is sort this list based on value density first, so for example there are 3 cats, 2 dogs and 1 mouse in the original array, but with unique this order is not correct dog->cat->mouse instead of cat->dog->mouse. How could I sort an array by density and then make it unique?

Community
  • 1
  • 1
CMOS
  • 2,727
  • 8
  • 47
  • 83

1 Answers1

4

First you calculate the cardinality (density) of each item:

$counts = array_count_values($array);

Then you sort the result descending, taking care to preserve keys:

arsort($counts);

And finally you get the (unique) keys in the descending sorted order:

$result = array_keys($counts);

See it in action.

Note that this method is very convenient, but you are limited to values that can be used as array keys (i.e., strings and integers). If the input contains other types of data (floats, objects, arrays) you will need to do this manually.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • This is a great answer! does exactly what I want, although I forgot to mention my array I am sorting is an array of arrays is this method still possible? The inner "arrays" are the things that need counting – CMOS Jun 04 '14 at 21:48
  • 1
    @CalvinMoss: I was just editing to address that. No, it's not possible to do it this way. And no matter what you do, you will have to define what exactly is the criterion that determines if the inner arrays are equal; start from there. Is it `==` equality? `===` equality? Perhaps it's recursive? Or something else entirely? – Jon Jun 04 '14 at 21:49
  • Is it possible to do this but on a specific value within an array perhaps? for example Array()->[0]->title["hello!"] [1]->title["hello!"] ? Thanks either way you helped alot – CMOS Jun 04 '14 at 21:52
  • @CalvinMoss: Now you have an array of objects?!?! Posting the correct array at first would be advisable. – AbraCadaver Jun 04 '14 at 21:54
  • @CalvinMoss: That last comment doesn't make much sense syntax-wise, and anyway it's hard to hit a moving target. If the actual problem is different than what I aimed to answer, please take the time to properly define it (either by editing this question or asking a new one). – Jon Jun 04 '14 at 21:59