Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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:

enter image description here

    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?

share|improve this question
add comment

2 Answers

maybe you can try this?

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

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

A much neater option for creating words is to use json_encode()

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

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.