Syed Balkhi
Syed Balkhi

Reputation: 52

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.

[{"total_count":17}]

I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:

https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22

Upvotes: 0

Views: 126

Answers (3)

LetterEh
LetterEh

Reputation: 26696

$json = "[{\"total_count\":17}]";

$arr = Jason_decode($json);
foreach ($arr as $obj) {
    echo $obj->total_count . "<br>";
}

Or use json_decode($json, true) if you want associative arrays instead of objects.

Upvotes: 0

Levi
Levi

Reputation: 2113

See this JS fiddle for an example of how to read it:

http://jsfiddle.net/8V4qP/1

It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:

<?php
    $result = json_decode('[{"total_count":17}]', true);
    print $result[0]['total_count'];
?>

if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.

Upvotes: 0

Dutow
Dutow

Reputation: 5668

PHP's json_decode returns an instance of stdClass by default.

For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:

$var = json_decode('[{"total_count":17}]', true);

After that, you can access the variable as $result[0]['total_count']

Upvotes: 2

Related Questions