[英]Retrieve object from array
我一直在嘗試閱讀我在Google上找到的其他示例,但我不確定100%確切地知道自己的位置。 我最近開始使用PHP和Javascript,並一直在構建基於Web的游戲。 確實沒什么特別的,但是我一次又一次從頭開始構建系統。 我能夠注冊,登錄,創建角色並加載房間。 我目前正在構建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初始化過程中利用它們。
就對象和數組而言,我的術語可能不多,但我保證我真的在嘗試!! 如果我必須描述自己理想的學習方式,那可能是我在火刑柱上放松自己的氣息。
您可以在解析數據后創建循環-
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的每個循環。 希望這個能對您有所幫助
我認為您想解析取回的數據。如有任何誤解,請提醒我。
碼
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.