Page 1 of 1

JSON and PHP - Help!

Posted: Tue May 13, 2014 9:58 pm
by codex561
Hello, I am making a bit of a project and I need help.
I got this JSON thing:
{"character_list":[{"name":{"first":"Dreadnaut","first_lower":"dreadnaut"},"battle_rank":{"percent_to_next":"0","value":"100"}}],"returned":1,"timing":{"character-ms":4,"total-ms":4}}
And I want to get the string equivalent of "First", in this case "dreadnaut" without quotes naturally.

How do I do that in PHP?

Re: JSON and PHP - Help!

Posted: Tue May 13, 2014 11:29 pm
by requinix
Decode it, first. You'll get back an object with a "character_list" property which is an array containing one object. (You can get associative arrays back instead of objects, if you prefer working with those.) If you think there might be more than one, use a foreach loop, otherwise you can go directly to the one that's there with [0].

Code: Select all

->character_list[0]->name->first_lower
If you want to get to character-ms or total-ms, decode the JSON to an associative array: it's nicer than dealing with the object.

Code: Select all

["timing"]["character-ms"]

Re: JSON and PHP - Help!

Posted: Wed May 14, 2014 11:37 am
by codex561
requinix wrote:Decode it, first. You'll get back an object with a "character_list" property which is an array containing one object. (You can get associative arrays back instead of objects, if you prefer working with those.) If you think there might be more than one, use a foreach loop, otherwise you can go directly to the one that's there with [0].

Code: Select all

->character_list[0]->name->first_lower
If you want to get to character-ms or total-ms, decode the JSON to an associative array: it's nicer than dealing with the object.

Code: Select all

["timing"]["character-ms"]
But how do I echo it out?

Re: JSON and PHP - Help!

Posted: Wed May 14, 2014 12:24 pm
by requinix
The same way you would echo out any value: just do it.

Code: Select all

echo $var->character_list[0]->name->first_lower;

Re: JSON and PHP - Help!

Posted: Fri May 16, 2014 10:42 pm
by codex561
requinix wrote:The same way you would echo out any value: just do it.

Code: Select all

echo $var->character_list[0]->name->first_lower;
I feel really stupid right now, I have never worked with JSON before but I tried this and it did not work

Code: Select all

$var='{"character_list":[{"name":{"first":"Dreadnaut","first_lower":"dreadnaut"},"battle_rank":{"percent_to_next":"0","value":"100"}}],"returned":1,"timing":{"character-ms":4,"total-ms":4}}';

	echo $var->character_list[0]->name->first_lower;  

Re: JSON and PHP - Help!

Posted: Fri May 16, 2014 11:32 pm
by requinix
How about we keep this to just one thread, okay?

You have to decode it. Re-read my first post.