简体   繁体   中英

PHP Get Value from Array with Value of Key

following problem: I want to build a mysql based language system.

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). 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? Do you have any hints? Or shall I simply select each phrase with each one query (performance problems with 100 quers per load?!)?

Cheers and Thanks!

That's a bad structure. Why not key your array with the phrase ID and the language? 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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