sort array

sort array

am 15.10.2007 21:20:48 von Paul

How can I sort a multi-dimensional array?
For instance:
a[Name], a[adress], a[number of messages].

How to sort on the item of number of messages?

Thanks for the help.

Re: sort array

am 15.10.2007 21:26:40 von Michael Fesser

..oO(Paul)

>How can I sort a multi-dimensional array?
>For instance:
>a[Name], a[adress], a[number of messages].
>
>How to sort on the item of number of messages?

Write your own comparison function and use usort() to apply it.

Micha

Re: sort array

am 15.10.2007 22:04:52 von zeldorblat

On Oct 15, 3:20 pm, "Paul" wrote:
> How can I sort a multi-dimensional array?
> For instance:
> a[Name], a[adress], a[number of messages].
>
> How to sort on the item of number of messages?
>
> Thanks for the help.

Something like this (untested):

usort($a, create_function('$a1,$a2', 'return $a1["number of messages"]
- $a2["number of messages"];'));

Re: sort array

am 16.10.2007 12:00:41 von Paul

"ZeldorBlat" schreef in bericht
news:1192478692.496334.152780@v29g2000prd.googlegroups.com.. .
> On Oct 15, 3:20 pm, "Paul" wrote:
>> How can I sort a multi-dimensional array?
>> For instance:
>> a[Name], a[adress], a[number of messages].
>>
>> How to sort on the item of number of messages?
>>
>> Thanks for the help.
>
> Something like this (untested):
>
> usort($a, create_function('$a1,$a2', 'return $a1["number of messages"]
> - $a2["number of messages"];'));
>
Thanks. My solution:
usort ($a, "mysort");
function mysort ($a, $b) {
if ($a['number of messages']<$b['number of messages']) return -1;
else if ($a['number of messages']>$b['number of messages']) return 1;
return 0;
}

Re: sort array

am 16.10.2007 20:05:23 von Michael Fesser

..oO(Paul)

>"ZeldorBlat" schreef in bericht
>news:1192478692.496334.152780@v29g2000prd.googlegroups.com. ..
>>
>> Something like this (untested):
>>
>> usort($a, create_function('$a1,$a2', 'return $a1["number of messages"]
>> - $a2["number of messages"];'));
>>
>Thanks. My solution:
>usort ($a, "mysort");
>function mysort ($a, $b) {
> if ($a['number of messages']<$b['number of messages']) return -1;
> else if ($a['number of messages']>$b['number of messages']) return 1;
> return 0;
>}

JFTR: I would drop the if-else and simply return the difference between
both values as in ZeldorBlat's function. The comparison function doesn't
necessarily have to return exactly -1, 0 or 1, the return value just has
to be lower than, equal to or greater than zero.

Micha