KingOfHeart Posted January 10, 2009 Share Posted January 10, 2009 Anyway to ignore the case when sorting an array? Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted January 10, 2009 Share Posted January 10, 2009 Try this: <?php /** * Sorts an associative array case-insensitively * * @author Daniel Egeberg * @param array $array * @return array * @license Released to public domain */ function asorti(array $array) { $copy = $array; $array = array_map('strtolower', $array); asort($array); foreach ($array as $index => $value) { $array[$index] = $copy[$index]; } return $array; } ?> I didn't test it, but it should work. Quote Link to comment Share on other sites More sharing options...
KingOfHeart Posted January 10, 2009 Author Share Posted January 10, 2009 That script worked nicely. I got another question now. I have a list of files, descriptions, and links. After the files are sorted, I need to match those descriptions and the links in the same order? How would I go about doing that, because so far it's not going right. Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted January 10, 2009 Share Posted January 10, 2009 Do you understand what my function does and why it works? It copies the array so it has the original. Then it makes all items in the original array lowercase (so that there is no difference in case). Then I used asort() to sort the array, but still preserve the index associativity. Because all items have the same index it's just a matter of looking up the original string from the copy array and put it back in. You can use more or less the same technique for what you require with the descriptions assuming they are in the same order that the filename array originally was. So... something like this perhaps: <?php $descriptions = array(/* something */); $filenames = asorti($filenames); $descCopy = $descriptions; $descriptions = array(); foreach(array_keys($filenames) as $index) { $descriptions[$index] = $descCopy[$index]; } Now $descriptions should have the same key order as $filenames does. Quote Link to comment Share on other sites More sharing options...
Mark Baker Posted January 10, 2009 Share Posted January 10, 2009 function caseInsensitiveSort($a, $b) { $a = strtolower($a); $b = strtolower($b); if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } $a = array('Apple', 'aardvark', 'ArMadillo', 'AARON', 'ARMour'); usort($a, 'caseInsensitiveSort'); foreach ($a as $value) { echo $value.'<br />'; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.