从数组键转换字符串不能用于多个段


Translate string from array keys won't work for more than one segment?

我只需要做一个简单的字符串翻译(url)与一个数组的键和他们的翻译。

试着这样做:

function ruta_iso( $ruta ) {
    $slugs = array(
        'noticia' => array(
            'es' => 'noticia',
            'en' => 'post'
        ),
        'pregunta' => array(
            'es' => 'pregunta',
            'en' => 'question'
        ),
        'consejo' => array(
            'es' => 'consejo',
            'en' => 'tip'
        ),
        'noticias' => array(
            'es' => 'noticias',
            'en' => 'news'
        )
    );

    $idioma_defecto = 'es';
    $idioma = 'en' ;
    if ( ($idioma != $idioma_defecto) && ($ruta == '/') ) {
        return "/$idioma";
    } else if( $idioma !=  $idioma_defecto ){
        foreach($slugs as $key => $slug){
            if ( ( strpos("/$key/", $ruta ) === false ) ){
            }else {
                $ruta = str_replace( "/$key/", '/'.$slug[$idioma].'/' , $ruta );
            }
        }
        $ruta = "/$idioma$ruta"; 
    } else {
    }
    return $ruta;
}
echo '-------Ruta Iso '.ruta_iso('/noticias/'); /* Works! */
echo ' -------Ruta Iso '.ruta_iso('/noticias/noticia/'); /* Nope.. */

可以在这里测试:

http://codepad.org/3w3Vmncg

似乎对一个slug起作用,但如果有多个slug就不行,甚至:

echo ' -------Ruta Iso '.ruta_iso('/noticias/blabla/'); /* Nope.. */

所以我不确定如何尝试,我的意思是,我没有打破foreach,为什么不是每个字符串检查?

toghts吗?

您也可以尝试这样做:

function ruta_iso( $ruta = '') {
    $slugs = array(
        'noticia' => array(
            'es' => 'noticia',
            'en' => 'post'
        ),
        'pregunta' => array(
            'es' => 'pregunta',
            'en' => 'question'
        ),
        'consejo' => array(
            'es' => 'consejo',
            'en' => 'tip'
        ),
        'noticias' => array(
            'es' => 'noticias',
            'en' => 'news'
        )
    );
    $idioma_defecto = 'es';
    $idioma = 'en' ;
    foreach( explode('/',  $ruta) as $data){
    if( !empty($data) ){
        if( array_key_exists($data, $slugs)){
            $result[] = $slugs[$data][$idioma];
        }else{
            $result[] = $data;
        }
    }
}
    $result = '/'.$idioma.'/'.implode('/', $result).'/';
    return $result;
}
echo '-------Ruta Iso '.ruta_iso('/noticias/');
echo ' -------Ruta Iso '.ruta_iso('/noticias/noticia/');
echo '-------Ruta Iso '.ruta_iso('/noticias/noticia/the-new');
结果:

-------Ruta Iso /en/news/ -------Ruta Iso /en/news/post/
-------Ruta Iso /en/news/post/the-new/