简体   繁体   English

PHP使用键的值从数组中获取值

[英]PHP Get Value from Array with Value of Key

following problem: I want to build a mysql based language system. 以下问题:我想建立一个基于mysql的语言系统。

To decrease loading time and increase performance I thought it would be the best, to first fetch all Language phrases into an array (which happens with mysqli fetch array). 为了减少加载时间并提高性能,我认为这是最好的,首先将所有Language短语提取到一个数组中(这与mysqli fetch数组有关)。 Then, if a language term is required, calling a function with the array as global variable. 然后,如果需要语言术语,则调用以数组为全局变量的函数。

My function for the array: 我对数组的功能:

$sql       = $db->query('SELECT * FROM lang_phrases WHERE phraseLanguageId = 1');
$phrases   = array();

while($row = $sql->fetch_array()) {
    $phrases[] = $row;
}

Now I've got this array: 现在我有了这个数组:

array(2) { 
    [0]=> array(8) { 
        [0]=> string(1) "1" 
        ["phraseId"]=> string(1) "1"
        [1]=> string(1) "1" 
        ["phraseLanguageId"]=> string(1) "1" 
        [2]=> string(4) "HOME" 
        ["phraseKey"]=> string(4) "HOME" 
        [3]=> string(10) "Homepage" 
        ["phraseContent"]=> string(10) "Homepage" 
    } 
    [1]=> array(8) { 
        [0]=> string(1) "2" 
        ["phraseId"]=> string(1) "2" 
        [1]=> string(1) "1" 
        ["phraseLanguageId"]=> string(1) "1" 
        [2]=> string(4) "BACK" 
        ["phraseKey"]=> string(4) "BACK" 
        [3]=> string(6) "Back" 
        ["phraseContent"]=> string(6) "Back" 
    } 
}

And thats my function: 那就是我的功能:

function l($key) {
    global $phrases;

    return PLACEHOLDER;
}

I wonder, how can I now search the array for "phraseKey" $key from the function and get the value? 我想知道,现在如何从函数中搜索“ phraseKey” $ key的数组并获取值? Do you have any hints? 你有什么提示吗? Or shall I simply select each phrase with each one query (performance problems with 100 quers per load?!)? 还是只需要在每个查询中选择每个词组(每次加载100个查询就会导致性能问题?!)?

Cheers and Thanks! 干杯,谢谢!

That's a bad structure. 那是一个糟糕的结构。 Why not key your array with the phrase ID and the language? 为什么不使用短语ID和语言来键入数组? eg 例如

$translations = array(
    'HOME' => array(
       'english' => 'Home',
       'french' => 'Maison',
       'german' => 'Haus"
    etc...

This eliminates the need for ANY searching. 这样就无需进行任何搜索。 You just look up directly by language/phrase ID. 您只需直接通过语言/短语ID查找即可。

May I suggest to retrive the phrases with 我可以建议用

while($row = $sql->fetch_array()) {
    $phrases[$row['phraseKey']] = $row;
}

Then in your function l($key) you can search them with 然后在function l($key)可以用

$t = isset($phrases[$key]) ? $phrases[$key] : null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM