简体   繁体   English

将 Json 转换为 Javascript 数组

[英]Converting Json to Javascript array

I am trying to write a game that uses javascript.我正在尝试编写一个使用 javascript 的游戏。 I am generating a list of words from a database and I have encoded the php using json_encode, and then echoed it into a javascript variable but it doesn't appear to be working, not sure what the issue appears to be.我正在从数据库中生成一个单词列表,我已经使用 json_encode 对 php 进行了编码,然后将其回显到 javascript 变量中,但它似乎不起作用,不确定问题是什么。

I have also tried parsing the variable with no luck.我也尝试过解析变量但没有运气。

<?php
    $sql = "SELECT word FROM `words` ORDER BY rand() LIMIT 0,2300";
    $result = mysqli_query($conn, $sql);

    $json_array = array();

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            $json_array[] = $row;
        }
        $tmp = json_encode($json_array);
    } else {
        echo "0 results";
    }

?>

//Javascript
function print() {

    var tmp = <?php echo $tmp ?>;
    document.write(Object.values(tmp));

}

I want to store the result into an array in javascript that is like:我想将结果存储到 javascript 中的数组中,如下所示:

array = ["word1","word2",...]数组 = ["word1","word2",...]

Then I can call like array.pop and get the word on the top.然后我可以像 array.pop 一样调用并获得顶部的单词。

Thanks谢谢

As mentioned by others this is due to referencing the object, you need to reference the value you want inserted into the array.正如其他人所提到的,这是由于引用了 object,您需要引用要插入到数组中的值。 You can print out the array to confirm this works:您可以打印出数组以确认其是否有效:

    var i;
    for (i = 0; i < tmp.length; i++) {
        words.push(Object.values(tmp)[i].word);
    }

    for(i=0; i < words.length; i++){
        document.writeln("word is: " + words[i]);
        document.writeln();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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