7
I have a function in php that returns it to me.
[{"id":81,"username":"usuarioteste23"}]
How can I save in a variable this ID and in another variable this Username?
Thank you.
7
I have a function in php that returns it to me.
[{"id":81,"username":"usuarioteste23"}]
How can I save in a variable this ID and in another variable this Username?
Thank you.
11
Do so:
$dados = json_decode('[{"id":81,"username":"usuarioteste23"}]', true);
$id = $dados[0]['id'];
$username = $dados[0]['username'];
What its function returns is a php string, containing serialized data in format JSON
.
JSON is used for you to exchange computer data. It uses javascript object notation (no javascript is required to read it). You can easily read it in multiple languages, such as PHP
, java
or python
.
In PHP, the function that decodes serialized data in JSON
is json_decode
. It will transform a data set of JSON
for PHP (array
, object
, int
, etc....).
In the example, I ethylized $dados[0]
because his json
has an object inside an array. So, we need to take 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 (given that you know that JSON is a type of notation similar to javascript types).
The array
no json is repeseated by []
.
The objeto
in json is represented by {}
json_decode return would result in the following statement, if made 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 for the json_decode
, which is the value true, que serve para definir se vamos decodificar o json para
arrayou
stdClass. Nesse caso trabalhei usando um
array`.
The return of this json_decode
with the second argument being true
, would be something like that statement:
$dados = array();
// Sem conversão para stdClass, usei um array simples
$dados[0] = array('id' => 81, 'username' => 'usuarioteste23');
0
Although the answer has already been given - and chosen - I think it valid to post another solution that is very elegant and that the language brings natively (it seems to have even 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 stated by someone in the comment below), but it will generate a WARNING (not error) 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 an array.
Note:
There is no relation to bad practice or bad idea - at least in this case - in using the built-in functionextract()
, since what you want get is a variable$id
and another call$username
. If you are afraid of collision of variable names, yourself spend a prefix for the third parameter of Extract(). The use of Extract() is popularly used in frameworks (like Laravel) and template Engines.
Having said that, the code should be better written that way:
<?php
$data = json_decode('[{"id":81,"username":"usuarioteste23"}]', true);
extract(array_pop($data));
-1 I am not commenting when I give negative, but this time I will make an exception. Array_pop only accepts variables (because the argument expects a reference). This code would generate an error. In addition to extract
is a bad idea, if json returns other names that could turn into inexperienced variables.
I will consider taking out the negative if you improve your response. For example, one can add the example that in php5.4 you could do this : json_decode($json, true)[0]
.
I didn’t understand why so many negative votes, Warning is easy to correct. + 1
The negative votes seemed fair to me yes, but I disagree more is to comment on them within the answer. The answer should be and only about the doubt problem. You should only fix the code problem and use the comment field or META. Join META, read what has been discussed there, learn how the community works. Do not misunderstand the downvotes they are not arbitrary (although there are times that people use it the wrong way). I will edit the answer is to leave only what is interesting. If you feel you need to discuss this go to META.
Now about your latest edition, no one said that extract
is the problem at all, maybe I haven’t been clear, but the problem is overwriting existing variables, maybe a closure resolves, lacked the explanation of why to use array_pop
. You stuck to justifying what is right and wrong, but you didn’t explain the code itself. Explain what array_pop
will make a difference, I do not know who gave the downvotes, but it is very likely that withdraw ;) - I am waiting for.
Simply use current
in place of array_pop
and I take the negative. And @rray, maybe it depends on the php version. This Warning is not released there for nothing, and maybe in some version can "evolve" to another error.
@Wallacemaxters didn’t say to leave the code on one line and let Warning cool if you have any should be dealt with. There is a lot in php that is not right or coherent see => http://answall.com/q/24992/91 I find it funny this, the documentation says that some functions are required to pass a reference but for some only generates Warning and works .... kind of bizarre. I’m not talking about not treating Warning :)
@Wallacemaxters on the "evolve" you spoke of, it is interesting to note that some use parentheses in these functions(I think the most common is the explode()
) not to generate Warning, but in php7 even with these additional parentheses occurs Warning, documentation
Browser other questions tagged php json array moodle
You are not signed in. Login or sign up in order to post.
This is all a string (json), it’s not?
– felipsmartins