有没有更好的方法来循环两个关联数组来匹配它们的值?


Is there a better way to loop two associative arrays to match their values?

我正在解析HTTP_ACCEPT_LANGUAGE头以获得用户的语言,我正在构建一个类来做到这一点。

实际上我构建了一个关联数组("$this->user_lang"),其中键是语言(例如"en-us", "it-it", "it-ch"等),值是质量因子(因此我可以订购语言)。然后我有另一个名为"$this->installed_langs"的关联数组,我在其中声明支持的语言和区域设置(以"en"=>"en_US","it"=>"it_IT"的形式)。

我想做的就是尝试将"$this->user_lang"中的一个键与"$this->installed_lang "中的一个键匹配(不考虑"-"后面的本地区域)并返回第一个出现(不考虑其他匹配情况)。

我最终使用了这种方法,但它似乎有点太复杂了…

public function show() {
    $g_locale = null;
    foreach ($this->user_lang as $lang => $q) {
        foreach($this->installed_langs as $valid => $locale) {
            if (strpos($lang, $valid) !== false) {
                if ($g_locale === null) $g_locale = $locale;
            }
        }
    }
    // debug:
    echo $g_locale;
}

我希望我已经解释得很清楚了,如果你需要更多的信息,请问我。

试试这个

public function show() {
    $g_locale = null;
    foreach ($this->user_lang as $lang => $q) {
        if ( array_key_exists( $lang, $this->installed_langs ) ) {
            $g_locale = $this->installed_langs[$lang];
        }
    }
}
function show() {
    $g_locale = null;
    foreach ($this->user_lang as $lang => $q) {
        $_key=explode($lang, '-'); // 'en-us' => 'array('en', 'us')
        $key=$_key[0]; // 'en'
        if ( array_key_exists( $key, $this->installed_langs ) ) {
            $g_locale = $this->installed_langs[$key];
        }
    }
}