Reply to Re: sort based on substring

Your name:

Reply:


Posted by Csaba Gabor on 01/23/08 01:51

On Jan 22, 6:05 pm, brechmos <brech...@gmail.com> wrote:
> I need to reply to my stupidty already...
>
> assume it is
>
> here1/there/200801/everywhere
> here2/there/200803/everywhere2
> here3/there/200802/everywhere3
>
> to...
>
> here1/there/200801/everywhere
> here3/there/200802/everywhere2
> here2/there/200803/everywhere3
>
> otherwise a simple sort command would work...
>
> On Jan 22, 12:04 pm, brechmos <brech...@gmail.com> wrote:
>
> > A bit of a dumb question. I have an array of directories and would
> > like to sort the array based on the third directory element...
>
> > e.g., from...
>
> > here/there/200801/everywhere
> > here/there/200803/everywhere2
> > here/there/200802/everywhere3
>
> > to...
>
> > here/there/200801/everywhere
> > here/there/200802/everywhere2
> > here/there/200803/everywhere3
>
> > I can think of lots of unelegant ways, is there an elegant one? (few
> > lines of code?)
>
> > Thanks...

Here is an alternate way, provided each
element is unique. Assume the array to
be sorted is in $array (4 lines, watch
for wrapping):


for ($aSort=array(),$i=0;$i<sizeof($array);++$i)
$aSort[$val]=preg_replace("'^([^/]*/){2}'","",$val=$array[$i]);
asort($aSort);
$array = array_keys ($aSort);


If there are duplicate values or the keys are not
indexed from 0 to sizeof($array)-1 then the for loop
should be a foreach and the sorting section becomes
a bit more involved:


$aSorted = array();
foreach ($array as $key=>$val)
$aSorted[$key]=preg_replace("'^([^/]*/){2}'","",$val);
asort($aSorted);
$aSorted = array_keys($aSorted);
foreach ($aSorted as &$key) $key=$array[$key];

and $aSorted now has the sorted $array
(perhaps also compare my example
at http://php.net/asort

If it is known that all the keys in
$array are non numeric,
then the last two lines could be combined to:
$aSorted = array_merge(array_flip (array_keys($aSorted)), $array);

Csaba Gabor from Vienna

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация