Welcome to WebmasterWorld Guest from 54.147.44.93

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Ordering PHP Array by Word Count

     

NoLimits

4:33 pm on May 27, 2008 (gmt 0)

10+ Year Member



I am trying to take the contents of a one dimensional php array and sort them in descending order, by the number of words in each string.

eg... here is my current array

array[0] = the dog was lazy
array[1] = the lazy dog
array[3] = wow that dog sure is lazy

I would like it to re-order as follows:

array[0] = wow that dog sure is lazy
array[1] = the dog was lazy
array[2] = the lazy dog

Any assistance, greatly appreciated.

coopster

5:55 pm on May 27, 2008 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



A user-defined sort may be your answer:
function cmp($a, $b) 
{
$a = strlen($a);
$b = strlen($b);
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
$array[0] = 'the dog was lazy';
$array[1] = 'the lazy dog';
$array[3] = 'wow that dog sure is lazy';
print_r($array);
usort [php.net]($array, 'cmp');
print_r($array);

RonPK

8:11 pm on May 27, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



coopster, shouldn't that be
str_word_count()
where you used
strlen()
?

coopster

10:08 pm on May 27, 2008 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



by the number of words in each string

I do believe you are correct, RonPK. str_word_count, split, something along those lines. Nice catch!

 

Featured Threads

Hot Threads This Week

Hot Threads This Month