3
How to transfer data from a JSON:
{"resultado":true,"cadastros":[{"id":"12345","nome":"Augusto","idade":"30"},{"id":"23411","nome":"Carlos","idade":"93"},{"id":"13451","nome":"Bruno","idade":"23"}],"mensagem":"Success"}
For variables in PHP resulting in:
`$id[0] = "12345"; $nome[0] = "Augusto"; $idade[0] = "30"; $id[1] = "23411"; $nome[1] = "Carlos"; $idade[1] = "93";`
and also the amount of records, which in total of this example are 3.
$registros = "3";
I tried using json_decode() along with foreach() but it didn’t work. I don’t know how to develop the logic.
<?php
$json = '{"resultado":true,"cadastros":[{"id":"12345","nome":"Augusto","idade":"30"},{"id":"23411","nome":"Carlos","idade":"93"},{"id":"13451","nome":"Bruno","idade":"23"}],"mensagem":"Success"}';
$a = json_decode($json, true);
echo $a;
?>
results in
Notice: Array to string Conversion in C: Program Files Easyphp-Devserver-14.1VC11 data localweb teste.php on line 4
Array line 4 is the echo $a;
What is the result of
json_decode()
?– Leonel Sanches da Silva
<?php
$json = '{"resultado":true,"cadastros":[{"id":"12345","nome":"Augusto","idade":"30"},{"id":"23411","nome":"Carlos","idade":"93"},{"id":"13451","nome":"Bruno","idade":"23"}],"mensagem":"Success"}';
$a = json_decode($json, true);
echo $a;
?>
results inNotice: Array to string conversion in C:\Program Files\EasyPHP-DevServer-14.1VC11\data\localweb\teste.php on line 4
Array
line 4 is the echo $a;– user3486019
I inserted your comment into the question. You can always edit the question to add details. Now that the comment is in question you can delete the comment here. I will also delete it when you see it. Welcome!
– Sergio
What appears when you test
var_dump($a);
, before theecho
?– Sergio
I was able to solve 90% of the problem with Filipe’s solution:
$a_Dados = json_decode($json, true);
echo $a_Dados["resultado"]."<br>"; //true
echo $a_Dados["cadastros"][1]["nome"]; //12345
Now missing to get the amount of records that are 3. How to proceed?– user3486019
@user3486019: testing
count($a_Dados["cadastros"]);
– Sergio