|
|
Re: sorting in PHP.
amit wrote:
> On Mar 26, 2:04 pm, Michael Fesser <neti...@gmx.de> wrote:
>> .oO(amit)
>>
>>> I'm getting data string as following. One of the columns is unixtime
>>> (10th element in each row) . How can I sort my array base on that?
>>> "310","true","6824567491","682087491","714469","xx xxx","xxxxx","xxxxx","xxxx","xxxxx","1206047432"
>>> "310","false","681224591","682087491","667256827", "yyyyy","yyyy","yyyy","yyyy","yyyy","12060478 37"
>> Write your own sorting function to use with usort().
>>
>> Micha
>
>
> Hi Micha,
>
> I did and for some reasons (I'm trying to undersetand why) I get this:
> (sort base on the last value which is unitime). It is not sorted in
> fact only the places are changed.
>
>
> Before sort:
> Array
> (
> [0] => 31042035360,send,
> 629956827,629956827,682087491,xxxx,xxx,xxxx,xxxx,x xxx, 1206043792
> [1] => 31042035360,send,
> 629956827,629956827,682087491,www,wwww,wwww,wwwww, wwwww, 1206045678
> [2] => 31042035360,send,
> 629956827,629956827,1070753141,ddddd,ddddd,ddddd,d dd,dddd, 1206044017
> )
>
> After sort:
> Array
> (
>
> [0] => 31042035360,send,
> 629956827,629956827,1070753141,ddd,dddd,ddddd,dddd d,dddd, 1206044017
> [1] => 31042035360,send,
> 629956827,629956827,682087491,wwww,wwwww,wwwwww,ww ww,wwww,1206045678
> [2] => 31042035360,send,
> 629956827,629956827,682087491,xxx,xxx,xxxx,xxxx,xx xx, 1206043792
> )
>
> Thanks.
I'ld convert that array in to two dimensions first:
<?php
echo "Before convert:\n";
print_r($a);
$b = array();
foreach ($a as $r) {
$b[]=explode(',',$r);
}
echo "After convert:\n";
print_r($b);
?>
Then you can use usort as follows:
<?php
echo "Before Sort:\n";
print_r($b);
function datecmp($a,$b) {
return ($a[10]==$b[10]?0  $a[10]<$b[10]?-1:1));
}
usort($b,datecmp);
echo "After Sort:\n";
print_r($b);
?>
Regards
Robin
|