I'm trying to convert this string :
$json = '[{"a":1,"b":2,"c":3,"d":4,"e":5}, {"a":6,"b":7,"c":8,"d":9,"e":10}]';
To an array of object. I've tried :
$test = json_decode($json, true);
echo sizeof($test); //traces 2 !
echo $test[0]["a"]; //doesn't echo anything!
How do i convert in PHP a json string to an array of object ??
asked Mar 29, 2012 at 17:36
Eric
10.7k14 gold badges75 silver badges112 bronze badges
2 Answers 2
Assuming that json is parsed into an array of objects, try
$test[0]->a
You can see this easily with
print_r($test)
which would output
Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
[1] => Array
(
[a] => 6
[b] => 7
[c] => 8
[d] => 9
[e] => 10
)
)
answered Mar 29, 2012 at 17:39
Aleks G
57.5k34 gold badges180 silver badges280 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
webbiedave
OP needs to remove the second parameter so that his code is:
$test = json_decode($json);Josh
For clarification, if the above output were the OP's output, then accessing an element via
$test[0]['a'] should work. However, if the second dimension were stdClass Objects instead of Array as per your output, then accessing an element via $test[0]->a would work.Aleks G
I tested his json_decode and the output is mine. The second level is object, not array.
json_decode returns an object. To convert the object to an array:
$test = (array)json_decode($json, true);
answered Mar 29, 2012 at 17:37
random_user_name
26.3k7 gold badges81 silver badges119 bronze badges
Comments
lang-php
$test[0]->a