Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

convert php associative array into javascript object

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...