Reputation: 308
This is my php function to change month names from english to other languages and this function is working fine.
function _ld($sqldate, $lang){
if(!$sqldate) $sqldate=date("Y-m-d");
$phpdate = strtotime( $sqldate );
$phpdate = date( 'd M Y', $phpdate );
$eng = array("Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
$kan = array("ಜನವರಿ", "ಫೆಬ್ರವರಿ", "ಮಾರ್ಚ್","ಏಪ್ರಿಲ್", "ಮೇ", "ಜೂನ್","ಜುಲೈ", "ಆಗಸ್ಟ್", "ಸೆಪ್ಟೆಂಬರ್","ಅಕ್ಟೋಬರ್", "ನವಂಬರ್", "ಡಿಸೆಂಬರ್");
$hin = array("जनवरी", "फ़रवरी", "मार्च","अप्रैल","मई","जून","जुलाई","आगस्त","सितम्बर","अकतूबर","नवेम्बर","दिसम्बर");
switch ($lang) {
case "kan" :
$to = $kan;
break;
case "eng" :
$to = $eng;
break;
case "hin" :
$to = $hin;
break;
default :
$to = $kan;
}
return str_replace($eng, $to, $phpdate);
}
echo _ld();
Now I want to simplify this function by adding languages to array (key=>values)
. Is this possible? If yes, how?
Please help me.
Upvotes: 1
Views: 61
Reputation: 446
Here's my attempt: https://repl.it/GbwN/4
So it took me a while to format the array correctly (a ton of one-by-one copy pasting).
We store the month at $month
and use it to iterate through our $months
's keys.
Removed your $eng
array because it felt redundant.
str_replace
now replaces string
instead of Array
.
Take note that $lang = 0
is for kan
while $lang = 1
is for hin
.
function _ld($sqldate, $lang){
if(!$sqldate) $sqldate=date("Y-m-d");
$phpdate = strtotime( $sqldate );
$month = date( 'M', $phpdate );
$phpdate = date( 'd M Y', $phpdate );
$months = array(
"Jan" => array("ಜನವರಿ", "जनवरी"),
"Feb" => array("ಫೆಬ್ರವರಿ", "फ़रवरी"),
"Mar" => array("ಮಾರ್ಚ್", "मार्च"),
"Apr" => array("ಏಪ್ರಿಲ್", "अप्रैल"),
"May" => array("ಮೇ", "मई"),
"Jun" => array("ಜೂನ್", "जून"),
"Jul" => array("ಜುಲೈ", "जुलाई"),
"Aug" => array("ಆಗಸ್ಟ್", "आगस्त"),
"Sep" => array("ಸೆಪ್ಟೆಂಬರ್", "सितम्बर"),
"Oct" => array("ಅಕ್ಟೋಬರ್", "अकतूबर"),
"Nov" => array("ನವಂಬರ್", "नवेम्बर"),
"Dec" => array("ಡಿಸೆಂಬರ್", "दिसम्बर")
);
switch ($lang) {
case "eng" :
return $phpdate;
break;
case "kan" :
$lang = 0;
break;
case "hin" :
$lang = 1;
break;
default :
$lang = 0;
}
return str_replace($month, $months[$month][$lang], $phpdate);
}
echo _ld("2017-02-29","hin");
You could add keys to each month's language like:
"Jan" => array("kan" => "ಜನವರಿ", "hin" => "जनवरी")
and change $lang = 0
to $lang = "kan"
to specify which array item we want to get.
I avoided this as I prefer not having the same thing repeated over and over again in my code.
Upvotes: 1