Jump to content

php array sorting help needed


kurbsdude

Recommended Posts

Hi,

 

I have a small problem. I have an array something like the following:

 

array[0] = "a"

array[1] = "b"

array[2] = "c"

array[3] = "a"

array[4] = "a"

 

Now I want to sort this array with respect to the frequency of occurrence of each character. So, basically this array should be rearranged as,

 

array[0] = "a"

array[1] = "a"

array[2] = "a"

array[3] = "b"

array[4] = "c"

 

How would this be done?

Link to comment
https://forums.phpfreaks.com/topic/138143-php-array-sorting-help-needed/
Share on other sites

i have never done this before but maybe array_count_values() could do it something like:

$array[0] = "a";
$array[1] = "b";
$array[2] = "c";
$array[3] = "b";
$array[4] = "b";
$temp = array_count_values($array);
arsort($temp);
$array = array();
foreach ($array as $value => $count) {
for ($i = 0; $i < $count; $i++) {
	$array[] = $value;			
}
}
print_r($array);

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.