How to read a Json file in php

Asked

Viewed 399 times

-5

{"acao":"muda-quantidade","dados":{"nova-quantidade":"2","referencia":"produto-um"}}

I’m learning Json,and I’m trying to read a json file in php and I’m not able to read the second array, (data), if anyone can give me a hand.

  • As you’re reading post the code?

1 answer

1


First of all your json has no array. Most likely it will arrive as string, there and only use the json_decode

$json = json_decode('{"acao":"muda-quantidade","dados":{"nova-quantidade":"2","referencia":"produto-um"}}');

$acao = $json->acao; //$acao agora tem o valor muda-quantidade
$dados = $json->dados;
$referencia = $dados->referencia; //$referencia agora tem o valor produto-um
//e por ai vai

Important and that the return of json_decode in your case will be a stdClass which is a Generic class so to speak.

Edit: one of its json properties is with hifen -, in this case to get the value Voce needs to do a cambalaxo $dados->{'nova-quantidade'}. Or better still if you can, exchange for some character accepted on behalf of variables.

Not to mix things up too much I won’t tell you why it’s like this, but research for: variables variable and string interpolation

  • that’s just what I need, but when I put it like this to get the new amount returns 0

  • $data = $reading->data; echo $data->new-quantity;

  • I was able to find the error , because of the sign ( - ), in the middle of new-quantity, error, removing the signal ( - ), function, there is some way to leave the signal ( - ) and it interpret and work ?

  • @Danieldallacolletta edited the answer, look at her

  • Opa, yes I saw your reply , thanks for the great help, I’ll see the best way I can adapt to my project I’ll take a look at what you commented , variable variables and string Interpolation.

  • if the answer helped you mark her as the best, so Voce also contributed to the site ^^

Show 1 more comment

Browser other questions tagged

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