Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order hindi characters

I have a page that renders alphabetically a directory of keywords (A, B, C, D....Z, 0, 1...9) and some of the keywords are in Hindi (devanagari).

My php code go through the alphabet array, sorts the keywords by first letter and renders columns for each letter with all the corresponding keywords that start with that same letter/number.

My problem is sorting the hindi alphabet array. My array is:

$hindi=array('क','ख','ग','घ','ङ','च','छ','ज','झ','ञ','ट','ठ','ड','ढ','ण','त','थ','द','ध','न','प','फ','ब','भ','म','य','र','ल','व','श','ष','स','ह','ळ','क','ष','ज्','ञ');

I have, for instance, the following keywords I wish to sort: एशिया खाना पकाना फोटोग्राफी भारतीय मसाला विध

I've tried out some approaches with no success and I'm rendering the hindi keywords just under "Hindi" column and unordered.

Is there a way to sort hindi characters using php?

like image 605
McRui Avatar asked Dec 29 '25 06:12

McRui


1 Answers

I assume the normal sorting doesn't work for some reason (the Hindi characters are shared among a couple languages, right?) Here's how to sort based on a user-defined character order

you need to usort() and call recursively to compare the next letter if the first ones match - like this

$words = explode(' ', "एशिया खाना पकाना फोटोग्राफी भारतीय मसाला विध");
usort($words, 'hindiCmp');

function hindiCmp($a, $b) {
    $hindi=array('क','ख','ग','घ','ङ','च','छ','ज','झ','ञ','ट','ठ','ड','ढ','ण','त','थ','द','ध','न','प','फ','ब','भ','म','य','र','ल','व','श','ष','स','ह','ळ','क','ष','ज्','ञ');
    $a1 = array_search(substr($a, 0, 1), $hindi); // first letter of a
    $b1 = array_search(substr($b, 0, 1), $hindi); // first letter of b
    if ($a1 < $b1) {
        return 1;
    } elseif ($a1 > $b1) {
        return -1;
    } else {
        if ((strlen($a) <= 1) && (strlen($b) <= 1)) { //end of both strings?
            return 0; // then it's an exact match
        } else { // otherwise compare the next characters
            return hindiCmp(substr($a, 1), substr($b, 1));
        }
    } 
}

Edit - for the curious- http://en.wikipedia.org/wiki/Nagari

"[Nagari is used by] Several Indian languages, including Sanskrit, Hindi, Marathi, Pahari (Garhwali and Kumaoni), Nepali, Bhili, Konkani, Bhojpuri, Magahi, Kurukh, Nepal Bhasa, and Sindhi. Sometimes used to write or transliterate Sherpa and Kashmiri. Formerly used to write Gujarati."

like image 155
msEmmaMays Avatar answered Dec 31 '25 21:12

msEmmaMays