How to store the value of the indexes of this JSON in variable?

7

I have a function in php that returns this to me.

[{"id":81,"username":"usuarioteste23"}]

How can I save a Username and variable in a variable?

Thank you.

    
asked by anonymous 21.01.2016 / 11:57

2 answers

11

Solution

Do this:

$dados = json_decode('[{"id":81,"username":"usuarioteste23"}]', true);

$id = $dados[0]['id'];

$username = $dados[0]['username'];

Explanation

What your function returns is a php string containing serialized data in JSON format.

JSON is used for you to exchange computer data. It uses the notation of javascript objects (no javascript is required to read it). You can read it easily in multiple languages, such as PHP , java or python .

In PHP, the function that decodes serialized data into JSON is json_decode . It will transform a set of data from JSON to PHP ( array , object , int , etc ...).

In the example, I used $dados[0] because its json has an object inside an array. So we need to get the index 0 to capture the first (and only) value of this array, which in turn contains an object with the id and username properties.

To make it easier to understand (since you know JSON is a type of notation similar to javascript types).

The array in json is represented by [] .

The objeto in json is represented by {}

The return of json_decode would result in the following statement, if it was done in php.

$dados = array();

// Object converte para stdClass

$dados[0] = (object)array('id' => 81, 'username' => 'usuarioteste23');

As you can see, I used a second argument passed to json_decode , which is the value true, que serve para definir se vamos decodificar o json para array ou stdClass . Nesse caso trabalhei usando um array '.

Returning this json_decode with the second argument being true would be something like this statement:

 $dados = array();

// Sem conversão para stdClass, usei um array simples

$dados[0] = array('id' => 81, 'username' => 'usuarioteste23');
    
21.01.2016 / 12:01
-1

Although the answer has already been given - and chosen - I find it worthwhile to post another solution that is quite elegant and that the language brings natively (it seems to have been built for your case):

$json = '[{"id":81,"username":"usuarioteste23"}]';
# agora você tem $id e $username
extract(array_pop(json_decode($json, true)));

Additional information:

The above code is not incorrect (as said by someone in the comment below), but it will generate a WARNING if Strict Standards is enabled:

PHP Strict Standards:  Only variables should be passed by reference

This is because, by default, PHP tries to pass the array_pop | array_shift argument by reference, and in this case, should be a variable, not a construct array.

  

Note:
  There is no relation to bad practice or bad idea - at least in this   case - in using the built-in function extract() , since what you want   get is a variable $id and another call $username . If you   you are afraid of colliding variable names yourself until   pass a prefix to the third extract () parameter. The use   of extract () is popularly used in frameworks (such as Laravel) and   template engines.

Having said that, the code should be spelled better this way:

<?php

$data = json_decode('[{"id":81,"username":"usuarioteste23"}]', true);

extract(array_pop($data));
    
21.01.2016 / 19:22