Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering PHP array by number of identical objects

Tags:

arrays

php

Is there anyway to order an array in this way? For example if I had this array:

$array = array("foo", "bar", "item", "item", "foo", "foo");

And I wanted to order it so that it was "foo", "foo", "foo", "item", "item", "bar" is there any way to do that?

like image 368
williamg Avatar asked Jun 14 '26 19:06

williamg


1 Answers

Would this do?

$array1 = array_count_values($array);
arsort($array1);
var_dump($array1);

will give you

array(3) {
  ["foo"]=>
  int(3)
  ["item"]=>
  int(2)
  ["bar"]=>
  int(1)
}

or do you necessarily need them as repeated values? if yes, you may go for something like:

usort($array,create_function('$a,$b',
    'return $GLOBALS["array1"][$a]<$GLOBALS["array1"][$b];'));

This is ugly code, but demonstrates the technique. It is also easy to make it good-looking with php 5.3 closures, but I don't know if you're on 5.3. That would look like this:

$acount=array_count_values($array = array("foo", "bar", "item", "item", "foo", "foo"));
usort($array,function($a,$b) use ($acount) { return $acount[$a]<$acount[$b]; });
like image 50
Michael Krelin - hacker Avatar answered Jun 16 '26 13:06

Michael Krelin - hacker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!