note 55591 modified in function.usort by thiago
| From: | thiago@php.net | Date: | Tue, 22 Jul 2008 19:13:23 +0000 |
| Subject: | note 55591 modified in function.usort by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142564@lists.php.net to get a copy of this message | ||
maybe someone can use this.
with that compare-function you can get this order:
string1, string2, ..., string10, string11, ...string22...
else the functions make something like
string10,string11,...string1,string20....
or
string1,string10,string11,string2,string20...
it's not the best solution, but works for my purpose...
<?php
function cmp($a,$b){
list($a)=explode(".",$a);
list($b)=explode(".",$b);
$s=0;
for($i=0;$i<=strlen($a);++$i){
if(is_numeric($a[$i])&&is_numeric($b[$i])){
$n=1;
$anum=$bnum=0;
while((is_numeric($a[$i])||is_numeric($b[$i]))&&
(strlen($a)>=$i||strlen($b)>=$i)){
if(is_numeric($a[$i])&&$i<=strlen($a)) $anum=$a[$i]+$anum*$n;
if(is_numeric($b[$i])&&$i<=strlen($b)) $bnum=$b[$i]+$bnum*$n;
$n*=10;
++$i;
}
if($n>1) --$i;
if($anum!=$bnum) return $anum<$bnum?-1:1;
}elseif($a[$i]!=$b[$i]) return $a[$i]<$b[$i]?-1:1;
}
}
?>
use it like this:
<?php
usort($array,"cmp");
?>
--was--
maybe someone can use this.
with that compare-function you can get this order:
string1, string2, ..., string10, string11, ...string22...
else the functions make something like
string10,string11,...string1,string20....
or
string1,string10,string11,string2,string20...
it's not the best solution, but works for my purpose...
<?
function cmp($a,$b){
list($a)=explode(".",$a);
list($b)=explode(".",$b);
$s=0;
for($i=0;$i<=strlen($a);++$i){
if(is_numeric($a[$i])&&is_numeric($b[$i])){
$n=1;
$anum=$bnum=0;
while((is_numeric($a[$i])||is_numeric($b[$i]))&&
(strlen($a)>=$i||strlen($b)>=$i)){
if(is_numeric($a[$i])&&$i<=strlen($a)) $anum=$a[$i]+$anum*$n;
if(is_numeric($b[$i])&&$i<=strlen($b)) $bnum=$b[$i]+$bnum*$n;
$n*=10;
++$i;
}
if($n>1) --$i;
if($anum!=$bnum) return $anum<$bnum?-1:1;
}elseif($a[$i]!=$b[$i]) return $a[$i]<$b[$i]?-1:1;
}
}
?>
use it like this:
<?
usort($array,"cmp");
?>
http://php.net/manual/en/function.usort.php