How to read this example of Json correctly?

Asked

Viewed 97 times

0

am have difficulty reading this json, because it has, in some returns, multiple addresses, image example below:

inserir a descrição da imagem aqui

Finally, can anyone help me? , I need to load or the Addressmain, highlighted in the image above.

Paths: Object->Result->0->Creditdata->0->Addresses->0->Addressmain Object->Result->0->Creditdata->0->Addresses->1->Addressmain

How I set up my code:

<?php

$json_data = json_decode(file_get_contents('arquivo2.json'));

foreach ($json_data->Result-> as $data) {
    echo '<br>País: ' .$data->CreditData-> ->Addresses-> ->Country;
    echo '<br>';

}
?>

My mistake is in the "way" the "0", "1" are breaking me... if anyone can give me a hint I thank

1 answer

4


JSON returns several array’s, and address is another one of them. You can do a foreach in this array or else always choose to access the first index, your code would look like this:

<?php

$json_data = json_decode(file_get_contents('arquivo2.json'), true);

foreach ($json_data["Result"] as $data) {
    echo '<br>País: ' .$data["CreditData"][0]["Addresses"][0]["Country"];
    echo '<br>';

}
?>

Also pass the Assoc parameter as true in the function json_decode to convert to an associative array.

  • Paul, I tried but it didn’t work ... gave error

  • What error returned? It can provide json as well?

  • Return this error: Warning: Invalid argument supplied for foreach() in C: Docker www index3.php on line 5 Call Stack # Time Memory Function Location 1 0.0030 361968 {main}( ) ... index3.php:0

  • Since json_decode is not returning an array, you have added the true parameter?

  • yes ... parameter this true

  • You can provide json for me to check the error?

  • Paulo, I got ... the error was result and has to be Result... but I follow with a problem still it continues loading only one of the address, it does not load the second form "automatically"...

  • @Paulovictor is missing a second loop inside the foreach to grab the values of the keys ..................... [0]["Country"]... [1]["Country"].. and so on.

  • As I said, he has the option to use the first input or make another loop, I gave only one example.

  • Paulo Victor has how to contact you?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.