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
https://forums.phpfreaks.com/topic/140286-sort-ignore-case/#findComment-734045
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/140286-sort-ignore-case/#findComment-734069
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
https://forums.phpfreaks.com/topic/140286-sort-ignore-case/#findComment-734081
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
https://forums.phpfreaks.com/topic/140286-sort-ignore-case/#findComment-734259
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.