Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_decode to array

Tags:

json

arrays

php

I am trying to decode a JSON string into an array but i get the following error.

Fatal error: Cannot use object of type stdClass as array in C:\wamp\www\temp\asklaila.php on line 6

Here is the code:

<?php $json_string = 'http://www.domain.com/jsondata.json';  $jsondata = file_get_contents($json_string); $obj = json_decode($jsondata); print_r($obj['Result']); ?> 
like image 831
Harsha M V Avatar asked Mar 02 '11 07:03

Harsha M V


People also ask

Does json_decode return array?

json - json_decode does not return array in php - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What does json_decode return?

The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.

What is the use of json_decode?

The json_decode() function is used to decode or convert a JSON object to a PHP object.

How can access JSON decoded data in PHP?

PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);


2 Answers

As per the documentation, you need to specify true as the second argument if you want an associative array instead of an object from json_decode. This would be the code:

$result = json_decode($jsondata, true); 

If you want integer keys instead of whatever the property names are:

$result = array_values(json_decode($jsondata, true)); 

However, with your current decode you just access it as an object:

print_r($obj->Result); 
like image 185
Stephen Avatar answered Sep 28 '22 04:09

Stephen


try this

$json_string = 'http://www.domain.com/jsondata.json'; $jsondata = file_get_contents($json_string); $obj = json_decode($jsondata,true); echo "<pre>"; print_r($obj); 
like image 26
diEcho Avatar answered Sep 28 '22 05:09

diEcho