Transfer the keys and values from a JSON to PHP variables

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 number of records, which in the total of this example are 3.

$registros = "3";

I tried using json_decode () along with foreach () but it did not work. I do not know how to develop 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 \ test.php on line 4

Array line 4 is echo $a;

    
asked by anonymous 02.04.2014 / 18:19

1 answer

1

Use json_decode with the second parameter "true", so an array will be returned associative, that is, items formed by a key pair and value, 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, please do a:

$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);
    
02.04.2014 / 18:30