kurbsdude Posted December 23, 2008 Share Posted December 23, 2008 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? Quote Link to comment https://forums.phpfreaks.com/topic/138143-php-array-sorting-help-needed/ Share on other sites More sharing options...
ratcateme Posted December 23, 2008 Share Posted December 23, 2008 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); Quote Link to comment https://forums.phpfreaks.com/topic/138143-php-array-sorting-help-needed/#findComment-722116 Share on other sites More sharing options...
PravinS Posted December 23, 2008 Share Posted December 23, 2008 User asort(array) function Quote Link to comment https://forums.phpfreaks.com/topic/138143-php-array-sorting-help-needed/#findComment-722184 Share on other sites More sharing options...
ratcateme Posted December 23, 2008 Share Posted December 23, 2008 asort() wont work it gives Array ( [0] => b [1] => c [2] => a [3] => a [4] => a ) Scott. Quote Link to comment https://forums.phpfreaks.com/topic/138143-php-array-sorting-help-needed/#findComment-722705 Share on other sites More sharing options...
Maq Posted December 23, 2008 Share Posted December 23, 2008 *Will not maintain the correlation of the indices. sort($array, SORT_STRING) Quote Link to comment https://forums.phpfreaks.com/topic/138143-php-array-sorting-help-needed/#findComment-722713 Share on other sites More sharing options...
PFMaBiSmAd Posted December 23, 2008 Share Posted December 23, 2008 I want to sort this array with respect to the frequency of occurrence of each character Quote Link to comment https://forums.phpfreaks.com/topic/138143-php-array-sorting-help-needed/#findComment-722789 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.