D&C Lug - Home Page
Devon & Cornwall Linux Users' Group

[ Date Index ][ Thread Index ]
[ <= Previous by date / thread ] [ Next by date / thread => ]

[LUG] PHP makes things easy



Compared to Perl, at least.

I quite like this little function:

Take a sequential array of numbers:
[0] = 562389856
[1] = 123521623
[2] = 898234234
[3] = 002342444
etc.
(zero padding is used to retain the format length).

The sequence is important as this is actually the alphabetical sequence of the 
text fields referenced by these long numbers (as output from the SQL), so it 
must be retained. However, the numbers must be presented in NUMERICAL order 
yet retain a link to the text fields which will remain in ALPHABETICAL order. 
Just sorting the sequential array would lose the alphabetical sequence and 
the text fields themselves are too long to use as keys.

If the sequential array is called $alphabet and the array containing the 
numerical sequence is called $numerical, the PHP code is simple:

$numerical = array_flip($alphabet);
ksort($numerical);

Can Perl/Python/Java/etc. do the same job in less code???
:-)

array_flip makes a new associative array where the numbers become keys and the 
sequence becomes values. Then ksort() sorts the associative array by KEY 
whilst retaining the keys and values intact. 

The live example can be seen in the Members Area:
http://www.dclug.org.uk/members/addlibrary.php
(But only if you've entered some books into the library!)

It ends up quite odd as the numerical sequence of links refer to an apparently 
chaotic sequence of references, 4 follows 25, follows 15, follows 19, follows 
0. etc.

Well, I thought it was cute anyway.

:-)

-- 

Neil Williams
=============
http://www.codehelp.co.uk
http://www.dclug.org.uk

http://www.biglumber.com/x/web?qs=0x8801094A28BCB3E3

Attachment: pgp00015.pgp
Description: signature


Lynx friendly