NBTX
NBTX

Reputation: 606

PHP: Getting associative array returns null, despite existing in var_dump

I have an array of 'servers' that I'm storing in a JSON file.

The JSON file looks like this: {"1":{"available":1,"players":0,"maxplayers":4}}

I retrieve this value with this:

$servers = (array) json_decode(file_get_contents("activeservers.json"));

However, when I try to access the array with $server = $servers[$id], $server is null. I noticed that the key is in quotes, so I also tried casting $id to a string, and surrounding it with quotes (") which didn't work.

Something to note, is that this code is returning "NULL":

foreach(array_keys($servers) as $key){
    var_dump($servers[$key]);
}

Upvotes: 2

Views: 1732

Answers (2)

André Ferraz
André Ferraz

Reputation: 1521

Your code is wrong. Also you don't need to type cast when doing a json_decode, you can instead set the second parameter to true more info here. Also you don't need to use the array_keys function in your foreach loop, try this.

$json    = '{"1":{"available":1,"players":0,"maxplayers":4}}';
$servers = json_decode($json, true);

foreach($servers as $key => $value) {
    print $value["available"];
}

Do a print_r($value) to get all the array keys available to use. Also you could take advantage of the $key variable to print out the array key of the parent array.

Upvotes: 2

NBTX
NBTX

Reputation: 606

Thanks, @Rizier123 (who solved the question).

Apparently passing TRUE as the second parameter to my json_decode function fixes the issue.

After checking the PHP documentation for json_decode() (PHP: json_decode), it seems that passing this parameter means that the resulting decoded array is automatically converted into an associative array (and this is recurring, meaning that this automatically happens for sub-arrays).

Edit: @Rizier123 also says that "you might want to read: stackoverflow.com/a/10333200 to understand a bit better why it is so "weird" and your method didn't work properly."

Upvotes: 1

Related Questions