Jump to content

sort, ignore case


KingOfHeart

Recommended Posts

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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 />';
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.