Assign JSON values to simple variables

0

I'm having trouble reading a JSON that I get:

{"data":{"charges":{"data":{"charges":[{"code":10006756,"dueDate":"13/09/2014","link":"https://www.teste.com.br"}]},"success":true}

I need to assign these values to my variables, this array will always have 1 record, it's the rule.

How to get all variables of it ( code , dueData , link and success ) and assign these values to simple variables? That is in my code I will have:

$code  = valordoJSON;
$dueData    = valordoJSON;
$link  = valordoJSON;
$sucesso    = valordoJSON;
    
asked by anonymous 11.09.2014 / 04:38

2 answers

6

You can use the json_decode function. This function gets a String in JSON format and returns you a object or array with the JSON properties.

Here's a simple example:

$json = '{"nome": "Bruno", "sobrenome": "da Silva", "idade": "37"}';

//transforma o JSON em um objeto
$objeto = json_decode($json);

echo 'Nome: ' . $objeto->nome;
echo 'Sobrenome: ' . $objeto->sobrenome;
echo 'Idade: ' . $objeto->idade;

If you do not want an object, you can transform JSON to a array , passing true to the second function parameter:

$json = '{"nome": "Bruno", "sobrenome": "da Silva", "idade": "37"}';

//transforma o JSON em um array
$array = json_decode($json, true);

echo 'Nome: ' . $array['nome'];
echo 'Sobrenome: ' . $array['sobrenome'];
echo 'Idade: ' . $array['idade'];
    
11.09.2014 / 05:08
0

It seems that the part "{"} "{" charges ": {" data ": {" charges "

<?php
$obj = json_decode('{"data":{"charges":[{"code":10006756,"dueDate":"13/09/2014","link":"https://www.teste.com.br"}]},"success":true}');

$code  = $obj->data->charges[0]->code;
$dueData = $obj->data->charges[0]->dueDate;
$link = $obj->data->charges[0]->link;
$sucess = $obj->success;

echo $code;
echo $dueData;
echo $link;
echo $sucess;
?>
    
11.09.2014 / 06:51