Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 as key value pair as such:

stuff : Ni, You 
stuff : Ta, Him or Her
stuff : Wo, I

Chinese and English words are loaded in a relational database.

PHP:

$wordsArray = array();               
while ($row = $sql->fetch_assoc()) {
    $wordsArray[$row['chinese']] = $row['english'];
}

Javascript: Here I want the $.each to output the key as a string, and not a number index. So when I tried var words = [<?php echo '"'.implode('","', $wordsArray).'"' ?>]; as an array, I got:

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

When I'm really looking for:

stuff : Ni, You 
stuff : Ta, Him or Her
stuff : Wo, I

So I changed words to be an object so that $.each could output key as string:

var words = {<?php echo '"'.implode('","', $wordsArray).'"' ?>};
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});

Which throws error: SyntaxError: Unexpected token ,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use json_encode() to make array as an json object like,

var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...