r/PHPhelp • • Oct 28 '21

Solved Help with JSON_DECODE

Hello together,

I am no professional developer but try to learn more in this field.

At the moment I try to convert a JSON result to a table, sadly I am stuck on the result from JSON_DECODE.

stdClass Object ( [data] => Array ( [0] => stdClass Object ( [type] => transaction [attributes] => stdClass Object ( [amount] => 10.00 [recipient] => [time] => stdClass Object ( [date_iso8601] => 2021-10-28T14:43:57+02:00 [unix] => 1635425037 ) (...) [1] => (...)

If I understand correctly, I can get the [type] = "transaction" over "$data->data", but how do I get for example the "amount"?
This confuses me, because there are class objects in class objects and I was not able to find a solution in the internet oder forums.

Thankful for every help and suggestion!

8 Upvotes

7 comments sorted by

10

u/MerlinTheGerman Oct 28 '21

if you pass true as the second argument to json_decode you will get an associative array instead of stdClass objects. See the documentation for json_decode.

$decoded = json_decode($data, true);

4

u/Jaypeare Oct 28 '21

Thank you! This was the missing part!

5

u/[deleted] Oct 28 '21

Don't think you need to do this. See my other reply.

4

u/MerlinTheGerman Oct 28 '21

You are correct, if you want to stick with the stdClass route something like your other reply works! Personally I find it more confusing with arrays/stdClass objects nested together (eg $data->data[0] uses both objects and array notation) so I just go straight to the associative array.

3

u/[deleted] Oct 28 '21

I don't suppose it matters since you're never going to get code completion in your IDE with stdClass or an array anyway.

jsonviewer.stack.hu is a godsend. Paste in your JSON and go to the viewer tab 😉

1

u/jeroennoten Oct 28 '21

A problem with this approach is that json_decode(‘[]’, true) and json_decode(‘{}’, true) result in the same value

9

u/[deleted] Oct 28 '21

$data->data[0]->attributes->amount

If I am reading that correctly.