从数组中检索对象

时间:2017-02-16 03:33:52

标签: javascript php arrays object

我一直试图阅读我通过谷歌发现的其他例子,但我并不是100%确定我完全理解我自己的位置。我最近开始使用PHP& Javascript并且一直在构建基于网络的游戏。没什么特别的,但我一直在从头开始构建系统。我能够注册,登录,制作角色,并加载房间。我目前正在构建NPC初始化程序,并尝试创建一个解决方案来处理一个房间内的多个NPC。我在getNPC.php中有这个代码,它返回了我对ajax请求所需的内容。

            while($row2 = mysqli_fetch_assoc($result2))
            {
                array_push($npcarray, array(
                    'id' => $row2['id'],
                    'name' => $row2['name'],
                    'location' => $row2['location'],
                    'switches' => $row2['switches'],
                    'switchesonoff' => $row2['switchon-off']
                ));
            }

因为浏览器开发人员的控制台记录了这个

,所以此刻我欣喜若狂
[{"id":"1","name":"Girl","location":"1","switches":"1","switchesonoff":"1"},
 {"id":"2","name":"Deer","location":"1","switches":"1","switchesonoff":"0"}]

唯一的问题是我不知道如何单独检索条目,因此我可以在实际的NPC初始化过程中使用它们。

就物体和阵列而言,我的术语可能已经关闭,但我保证我真的在努力!如果我不得不描述我理想的学习风格,那么我可能会在焚烧火柴时不必自我。

2 个答案:

答案 0 :(得分:0)

您可以在解析数据后创建循环 -

var data = JSON.parse(data); // Use your response of ajax in data

    for (var i = 0; i < data.length; i++) {

       console.log(data[i].id)
       console.log(data[i].name)
    }

您还可以使用每个jquery循环。 希望这会对你有所帮助

答案 1 :(得分:0)

我觉得你要解析你的回复数据。如果有任何误解,请提醒我。

<强>码

while($row2 = mysqli_fetch_assoc($result2))
        {
            array_push($npcarray, array(
                'id' => $row2['id'],
                'name' => $row2['name'],
                'location' => $row2['location'],
                'switches' => $row2['switches'],
                'switchesonoff' => $row2['switchon-off']
            ));
        }
//after async
for(var key in npcarray) console.log(npcarray[key].id);//Replace id with what you want.
相关问题