如何按键搜索PHP数组并返回其值? [重复]

问题描述 投票:0回答:3

这个问题在这里已有答案:

我编写了一个简单的Translate类,它存储一个常量关联数组。关键是源语言,值是目标语言的翻译。如何在此数组中搜索给定键并返回其值(此处为translation)?

namespace utils;

abstract class Translate
{
    private const WORDS = array (
        "Welcome" => "خوش آمدید", 
        "Access denied" => "دسترسی امکان پذیر نمی باشد",

    ) ;



    /**
     * Returns the translation of the given word. 
     * Returns the given word as is if $dont_translate is set to false
     * @param string $word
     * @param boolean $dont_translate
     */
    public static function get($word, $dont_translate = false){
        $data = WORDS;        
        foreach($row as $data) {

        }
    }
}

在我的代码中,我使用此函数如下:

if($loggedIn) {
    echo '<p class="center">'. Translate::get('Welcome ')  . $username;
}
else {
    die("<p class='center'>" . Translate::get('Access denied ') . " </p>");
}
php arrays translation
3个回答
2
投票

我已经改变了第二个参数,因为它可能会让人感到困惑,因为它具有双重负面条件(不翻译为假是恕我直言,而不是翻译是真的)...

/**
 * Returns the translation of the given word.
 * Returns the given word as is if $translate is set to false
 * @param string $word
 * @param boolean $translate
 */
public static function get($word, $translate = true){
    $word = trim($word);
    if ( $translate )   {
        if ( isset(self::WORDS[$word]) )    {
            $trans = self::WORDS[$word];
        }
        else    {
            $trans = false;
        }
    }
    else    {
        $trans = $word;
    }
    return $trans;
}

如果翻译单词不存在,则返回false,更改返回原始值很容易。

刚刚在输入中添加了一个trim(),因为我注意到你的例子有空格。

虽然我不是这种编码风格的忠实粉丝(它使代码不易清晰),如果你使用PHP 7 null coalesce operator,你可以使用稍短的...

public static function get($word, $translate = true){
    return ( $translate )?(self::WORDS[trim($word)]??false):trim($word);
}

1
投票

您最好开始阅读PHP数组的手册:http://php.net/manual/de/language.types.array.php

但这里没关系是一个友好的初学者代码片段:

if (isset(self::WORDS['Access denied'])) {
    echo self::WORDS['Access denied'];
} else {
    echo 'No key found'
}

1
投票

试试这个

public static function get($word, $dont_translate = false){
    $data = WORDS;        
    $str = isset($data[$word]) ? $data[$word] : $word;
     return $str;
}
© www.soinside.com 2019 - 2024. All rights reserved.