0

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 ??

3
  • Assuming that json is parsed into an array of objects, try $test[0]->a Commented Mar 29, 2012 at 17:38
  • Thanks, you should have made a "real" answer ;) Commented Mar 29, 2012 at 17:39
  • Ok, I posted it as an answer :) Commented Mar 29, 2012 at 17:40

2 Answers 2

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
        )

)
Sign up to request clarification or add additional context in comments.

3 Comments

OP needs to remove the second parameter so that his code is: $test = json_decode($json);
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.
I tested his json_decode and the output is mine. The second level is object, not array.
1

json_decode returns an object. To convert the object to an array:

$test = (array)json_decode($json, true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.