Discussion: sorting in PHP.
Afficher un message
Vieux 26/03/2008, 23h17   #3
Alexey Kulentsov
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: sorting in PHP.

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","120604783 7"


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";

--------------------------------



?>
  Réponse avec citation
 
Page generated in 0,10435 seconds with 9 queries