简体   繁体   中英

Load database values as k:v pairs into PHP, and then into JavaScript array

I'm trying to load Chinese words as keys, and their English translations as values from a database into a php array so then I can use them on the client side in JavaScript. So I load the PHP key:value pairs into the JavaScript array and try to output the results.

Database setup:

在此处输入图片说明

    include 'php/DbConnect.php';
    $sql = $mysqli->query(
     "SELECT t.*, v.* 
     FROM task t 
     INNER JOIN vocabtask vt ON (t.id = vt.taskid)
     INNER JOIN vocab v ON (v.id = vt.vocabid)
     WHERE vt.taskid = 1");
    $wordsArray = array();

    while ($row = $sql->fetch_assoc()) {
        $wordsArray[$row['chinese']] = $row['english'];
        //echo key : value pair
        echo "<br>".key($wordsArray) . ":" . $wordsArray[$row['chinese']];
    }
    var_dump($wordsArray);
    mysqli_close($mysqli);  

Echo output gives Ni as key for each value, which is wrong:

Ni: You
Ni: Him or Her
Ni: I

var_dump, however, gives correct key:value pairing:

array (size=3)
  'Ni' => string 'You' (length=3)
  'Ta' => string 'Him or Her' (length=10)
  'Wo' => string 'I' (length=1)

JavaScript:

    var words = [<?php echo '"'.implode('","', $wordsArray).'"' ?>];

    $.each(words, function(key, value) {
        console.log('stuff : ' + key + ", " + value);
    }); 

Console.log gives numbers for keys, and not the Chinese keys:

stuff : 0, You 
stuff : 1, Him or Her
stuff : 2, I

Question: if the php dump shows appropriate pairings of key (the Chinese word) to value (the English word), why am I getting this different outputs?

implode() is not printing the keys of $wordsArray which is why the var words doesn't have the correct keys.

What you're really trying to achieve here is a string representation of a PHP array with Javascript syntax. A function that will do that for you is json_encode()

<?php echo "var words = ". json_encode($wordsArray) . ";";?>

More info here: http://au2.php.net/json_encode

And the reason this line doesn't work:

echo "<br>".key($wordsArray) . ":" . $wordsArray[$row['chinese']];

Is because the key() function doesn't move the array pointer, hence you get a repeat of the same array key.

maybe you can try this?

var words = 
[<?php $result = [];
foreach($wordsArray as $key=>$value){
   $result[] = '"'.$key.'":"'.$value.'"';
}
echo implode(',', $result)
?>]

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