我在PHP中創建一個JSON對象,並將其發送回主頁:如何獲取json對象內的數組的長度?
$invSlots = array();
$invSlots['slots'] = array();
for($i = 1; $i < $player_max_slots+1; $i++){ //player max slots comes from db
$invSlots['slots'][$i] = $inventory_info3[$i];
}
$json = $invSlots;
$encoded = json_encode($json);
die ($encoded);
和後的反應是這樣的:
{"slots": {
"1": "1",
"2": "0",
"3": "0",
"4": "4",
"5": "0",
"6": "0",
"7": "3",
"8": "0",
"9": "0",
"10": "0",
"11": "2",
"12": "0"
}
}
我試着去得到插槽的數量,如下所示:
var myResponse = JSON.decode('(' + responseText + ')'); //decode server json response
maxSlots = myResponse.slots.length; //set max slots
但myResponse.slots.length只是返回undefined,我該如何解決它?
'slots'不是一個數組,它的另一個對象。 –
內部數組從0開始,但是因爲你迫使它從1開始,它會變成一個對象。您將不得不將數組重置爲0,或者使用正確的數字手動向數組添加「長度」鍵。 – Zimzat