为了使用多语言,我们有这样的设置:
values like: title (as in: SELECT title FROM ...) and, change: $title (as in: $title=$rows["title"]; )
为:
有没有PHP /快速解决方案?
答案 0 :(得分:1)
您可以像这样创建语言映射:
// lets assume that we need not only title but also description
$lang2Fields = array(
1 => ['title' => 'title', 'description' => 'description'], // en
2 => ['title' => 'title_fr', 'description' => 'description_fr'], // fr
3 => ['title' => 'title_ru', 'description' => 'description_ru'], // ru
// ... other languages
);
// try to get language id from cookie
$defaultLanguage = 1; // en
$language = !empty($_COOKIE["langID"]) ? $_COOKIE["langID"] : $defaultLanguage;
$fields = !empty($lang2Fields[$language]) ?
$lang2Fields[$language] : $lang2Fields[$defaultLanguage];
$titleField = $fields['title'];
$descriptionField = $fields['description'];
// later we can use these field names into your queries
// $sql = "SELECT ".$titleField.", ".$descriptionField." FROM ...";
// $$titleField = $rows[$titleField];
答案 1 :(得分:1)
也许是这样的?
<?
$arrMapCookieToLang = [
1 => "",
2 => "fr",
3 => "es",
];
function langify($item, $cookieLangId = null) {
global $arrMapCookieToLang;
if (empty($cookieLangId)) {
$cookieLangId = 1;
if (array_key_exists("cookie-language-id", $_COOKIE)) {
$cookieLangId = $_COOKIE["cookie-language-id"];
}
}
$langCode = $arrMapCookieToLang[$cookieLangId];
if (empty($langCode)) return $item;
return "{$item}_{$langCode}";
}
$sql = "SELECT ".langify("title")." FROM ...";
$title = $rows[langify("title")];
// OR:
$sql = "SELECT ".langify("title")." AS title FROM ...";
$title = $rows["title"];
但是请注意,每种语言都有一个列可能不是一个很好的做法。你应该像alexander.polomodov建议的那样去。
此外,即使您选择继续使用当前结构 - 考虑将$ arrMapCookieToLang和langify()函数放在一个类中(全局变量和函数都是恶意的)