Transfer keys and values ​​from a JSON to PHP variables

Question:

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 PHP variables with the result:

`$id[0] = "12345"; $nome[0] = "Augusto"; $idade[0] = "30"; $id[1] = "23411"; $nome[1] = "Carlos"; $idade[1] = "93";`

and also the number of records, which in the total for this example are 3.

$registros = "3";

I tried using json_decode() together 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"},{"i‌​d":"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 echo $a;

Answer:

Use json_decode with the second parameter "true", this will return an associative array, that is, items formed by a key and value pair, in which each key has an associated value.

An example where $url is the link to json.

$a_Dados = json_decode(file_get_contents($url), true);
echo $a_Dados["resultado"]; //true
echo $a_Dados["cadastros"][0]["id"]; //12345

If necessary, do a for:

$a_Dados = json_decode(file_get_contents($url), true);
for($i=0; $i<count($a_Dados["cadastros"]); $i++){
    echo $a_Dados["cadastros"][$i]["id"];
}

If you have a variable encoded in json, change the following line:

 $a_Dados = json_decode($variavel_codifica_json,true);
Scroll to Top