Discussion: sorting in PHP.
Afficher un message
Vieux 27/03/2008, 00h01   #5
amit
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sorting in PHP.

On Mar 26, 2:17pm, Alexey Kulentsov <a...@inbox.ru> wrote:
> amit wrote:
> > 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"

>
> bad way but illustrates usort()
> --------------------------------
> define('TS_REGEXP','/^(?:"[^"]*",){10}"(\d+)"$/');
>
> // data
> $d=array
> ('"310","true","6824567491","682087491","714469"," xxxxx","xxxxx","xxxxx","xxxx","xxxxx","1206047432 "'
> ,'"310","false","681224591","682087491","667256827 ","yyyyy","yyyy","yyyy","yyyy","yyyy","1206047837 "'
> );
>
> // Extract and compare timestamps from two rows
> function rowCompare($a,$b)
> {
> preg_match(TS_REGEXP,$a,$ar)reg_match(TS_REGEXP, $b,$br);
> return (int)$ar[1] > (int)$br[1];
>
> }
>
> // sort array
> usort($d,'rowCompare');
> // sorted array in $d
> --------------------------------
>
> good way but it is depends where you will to use results.
> --------------------------------
> define('TS_REGEXP','/^(?:"[^"]*",){10}"(\d+)"$/');
>
> // data
> $d=array
> ('"310","true","6824567491","682087491","714469"," xxxxx","xxxxx","xxxxx","xxxx","xxxxx","1206047432 "'
> ,'"310","false","681224591","682087491","667256827 ","yyyyy","yyyy","yyyy","yyyy","yyyy","1206047837 "'
> );
>
> // additional array
> $d1=array();
>
> // make index
> foreach($d as $data)
> {
> preg_match(TS_REGEXP,$data,$key);
> $d1[(int)$key[1]]=$data;}
>
> ksort($d1);
> // sorted array in $d1
> --------------------------------
>
> one more index, no data copy in it:
> --------------------------------
> ...
> $ts_index=array();
> foreach($d as $index=>$data)
> {
> preg_match($r,$data,$key);
> $ts_index[(int)$key[1]]=$index;
>
> }
>
> ksort($ts_index);
> $ts_index=array_values($ts_index);
>
> // loop ordered by timestamp
> foreach($ts_index as $index)
> echo $d[$index]."\n";
>
> --------------------------------
>
> ?>



Thanks indeed for you solution using regular experession but I'm
afraid to get into trouble later since I'm not familiar with RE yet.

Any other suggestions?

Regards.

  Réponse avec citation
 
Page generated in 0,06315 seconds with 9 queries