Thaiscorpion
Thaiscorpion

Reputation: 479

How to get length of an array that is inside a json object?

I create a json object in php and send it back to the main page:

$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);

And the post response is this:

{"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"
   }
}

Im trying to get the amount of slots like so:

var myResponse = JSON.decode('(' + responseText + ')'); //decode server json response
maxSlots = myResponse.slots.length; //set max slots

but myResponse.slots.length just returns undefined, how can i fix it?

Upvotes: 2

Views: 8080

Answers (3)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

slots is not an array, it's another object. If it were being serialized as an array it would probably look more like:

{ "slots": 
    [
        { "0": "1" },
        { "1": "0" },
        { "2": "0" },
        ...
    ]
}

Or even just:

{ "slots": [ "1", "0", "0" ] }

Try changing your loop to:

for ($i = 0; $i < $player_max_slots; $i++) { //player max slots comes from db
    $invSlots['slots'][$i] = $inventory_info3[$i];
}

As Zimzat said in a comment above, once your array's indices start at 0 you should get an array of slots when you serialize your object to JSON.

Actually, according to some guy at the php.net forums, you need to be aware of index arrays.

<?php
echo json_encode(array("test","test","test"));
echo json_encode(array(0=>"test",3=>"test",7=>"test"));
?>

Will give :

["test","test","test"]
{"0":"test","3":"test","7":"test"}

Arrays are only returned if you don't define an index, or if your indexes are sequential and start at 0.

Upvotes: 1

Tim Rogers
Tim Rogers

Reputation: 21713

You've declared an associative array, not an indexed array. So you can't use length.

To get the count from an associative array, you need to iterate through its keys:

var count=0;
for (var key in $invSlots['slots'])
    count++;

Upvotes: 1

qwertymk
qwertymk

Reputation: 35276

You can make a little function:

function len(obj) {
    var ret = 0;
    for (var i in obj) ret++;
    return ret;
}

var maxSlots = len(myResponse.slots)

Upvotes: 0

Related Questions