JSON array foreach loop with "where" attribute - php

I have a JSON array directly from an API and one piece of it looks like this:
{
"type": "champion",
"version": "4.4.3",
"data": {
"Aatrox": {
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "the Darkin Blade",
"stats": {
"armor": 14.0,
"armorperlevel": 3.8,
"attackdamage": 55.0,
"attackdamageperlevel": 3.2,
"attackrange": 150.0,
"attackspeedoffset": -0.04,
"attackspeedperlevel": 3.0,
"crit": 0.0,
"critperlevel": 0.0,
"hp": 395.0,
"hpperlevel": 85.0,
"hpregen": 5.75,
"hpregenperlevel": 0.5,
"movespeed": 345.0,
"mp": 30.0,
"mpperlevel": 45.0,
"mpregen": 0.0,
"mpregenperlevel": 0.0,
"spellblock": 30.0,
"spellblockperlevel": 1.25
}
},
and then it simply repeats this for every other champion. I used cURL to turn that into a PHP array, which looks like this:
$url="api_url_blah";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
$array = json_decode($result, true);
From there, I made a foreach loop to list all the champions and their "armor" stat, however the armor won't display but the champion name does:
$i = 1;
foreach($array['data'] as $champs)
{
echo $champs['id']. "<br>";
foreach($champs['stats'] as $stats) {
echo $stats['armor'];
}
$i++;
}
As I said, the champion name comes up but the second foreach loop is returning nothing. Also, I was wondering what would be the most convenient way to make it so (after this works) I can call just one champion's stats based on a PHP variable and not all 118 of them at one time.
This is the var_dump() of the array:
array(3) { ["type"]=> string(8) "champion" ["version"]=> string(5) "4.4.3" ["data"]=> array(118) { ["Aatrox"]=> array(5) { ["id"]=> string(6) "Aatrox" ["key"]=> string(3) "266" ["name"]=> string(6) "Aatrox" ["title"]=> string(16) "the Darkin Blade" ["stats"]=> array(20) { ["armor"]=> float(14) ["armorperlevel"]=> float(3.8) ["attackdamage"]=> float(55) ["attackdamageperlevel"]=> float(3.2) ["attackrange"]=> float(150) ["attackspeedoffset"]=> float(-0.04) ["attackspeedperlevel"]=> float(3) ["crit"]=> float(0) ["critperlevel"]=> float(0) ["hp"]=> float(395) ["hpperlevel"]=> float(85) ["hpregen"]=> float(5.75) ["hpregenperlevel"]=> float(0.5) ["movespeed"]=> float(345) ["mp"]=> float(30) ["mpperlevel"]=> float(45) ["mpregen"]=> float(0) ["mpregenperlevel"]=> float(0) ["spellblock"]=> float(30) ["spellblockperlevel"]=> float(1.25) } }

You don’t need a second foreach loop. The following code should work:
$i = 1;
foreach($array['data'] as $champs){
echo $champs['id'] . "<br/>" . $champs['stats']['armor'] . "<br/>";
$i++;
}

Related

Further data retrieving inside array of JSON using PHP

I have a JSON file I want to fill in a table, but can't quite figure out how to retrieve the data inside and loop it through an array to get in a table I made.
This is my JSON file: test.JSON:
{
"data":{
"Chair":{
"id":24,"key":"Chair","name":"Chair","title":"oak home made"
},
"Table":{
"id":37,"key":"Table","name":"Table","title":"round white table"
},
"Closet":{
"id":18,"key":"Closet","name":"Closet","title":"big and red"
},
"Sofa":{
"id":110,"key":"Sofa","name":"Sofa","title":"room for five persons"
}
},
"type":"furniture","version":"1.1.0"
}
Then with PHP I used this: test.PHP:
$url = 'test.json';
$result=file_get_contents($url);
$decoded=json_decode($result, true);
var_dump($decoded);
This is what I get:
array(3) { ["data"]=> array(4)
{
["Chair"]=> array(4)
{ ["id"]=> int(24) ["key"]=> string(5) "Chair" ["name"]=> string(5) "Chair" ["title"]=> string(13) "oak home made" }
["Table"]=> array(4)
{ ["id"]=> int(37) ["key"]=> string(5) "Table" ["name"]=> string(5) "Table" ["title"]=> string(17) "round white table" }
["Closet"]=> array(4)
{ ["id"]=> int(18) ["key"]=> string(6) "Closet" ["name"]=> string(6) "Closet" ["title"]=> string(11) "big and red" }
["Sofa"]=> array(4)
{ ["id"]=> int(110) ["key"]=> string(4) "Sofa" ["name"]=> string(4) "Sofa" ["title"]=> string(21) "room for five persons" }
}
["type"]=> string(9) "furniture" ["version"]=> string(5) "1.1.0"
}
Then I am trying to retrieve "Chair", "Table", "Closet" and "Sofa", but I don't know how to do it. When I try this:
foreach ($decoded as $key => $value) {
echo "key: ".$key;
echo "</br></br>";
echo "value: ".$value;
echo "</br></br>";
return;
}
I get:
key: data
value: Array
Can someone help me get "Chair", "Table", "Closet" and "Sofa", including each of thoses' id, key, name and title?
I have received guides, but they won't help me because I feel like this type of "array" is different then the links for guides I receive.
Thanks!
You are looping through the array on the top most level, while you want to be a level lower than that to be able to loop through all the elements of data, like this:
foreach ($summonerDecoded2['data'] as $key => $value)
{
echo "key: ".$key."</br>";
echo "value id: ".$value['id']."</br>";
echo "value key: ".$value['key']."</br>";
echo "value name: ".$value['name']."</br>";
echo "value title: ".$value['title']."</br>";
}
You can just do this:
$url = 'test.json';
$result=file_get_contents($url);
$decoded = json_decode($result, true);
foreach ( $decoded["data"] as $key => $value) {
echo $value[ "key" ];
echo "<br />";
//You can access data by:
/*
echo $value[ "id" ];
echo $value[ "key" ];
echo $value[ "name" ];
echo $value[ "title" ];
*/
}
This will result to:
Chair
Table
Closet
Sofa

PHP loop through nested JSON to find value

I am trying to loop through nested JSON data to find a name with a specific string and extract the string value associated with that. In this case the name string is "myKey" and the value string is "12345678".
After looking at several similar questions and documentation, I have tried different approaches such as doing it with objects or associative arrays, but still end up not being able to get to the information I want or receive errors.
Types of errors:
Notice: Array to string conversion
Warning: Invalid argument supplied for foreach()
Trying to get property of non-object
Here is a snippet of the decoded JSON using $myObj = json_decode($result);
object(stdClass)#4 (3) {
["info"]=>
object(stdClass)#5 (10) {
.
.
.
}
["stuff"]=>
array(1) {
.
.
.
}
["result"]=>
array(3) {
[0]=>
object(stdClass)#7 (3) {
["name"]=>
["value"]=>
["description"]=>
}
[1]=>
object(stdClass)#8 (2) {
["name"]=>
string(4) "Units"
["value"]=>
array(2) {
[0]=>
array(6) {
[0]=>
object(stdClass)#9 (3) {
.
.
.
}
.
.
.
[5]=>
object(stdClass)#14 (2) {
["name"]=>
string(10) "Components"
["value"]=>
array(1) {
[0]=>
array(14) {
[0]=>
object(stdClass)#15 (3) {
.
.
.
}
[1]=>
object(stdClass)#16 (3) {
["name"]=>
string(5) "myKey"
["value"]=>
string(8) "12345678"
["description"]=>
}
.
.
.
Here is a snippet of the PHP code I tried:
$myObj = json_decode($result);
// or I have tried
// $myObj = json_decode($result, true);
// here are different snippets of code I tried
foreach($myObj->result as $test) {
echo '<pre>';
print_r($test->name);
echo "<br>";
if ($test->name == "Units") {
$resultName = $test->name;
echo $resultName . "<br>";
}
echo '</pre>';
}
/*
foreach($myObj->result as $test) {
echo $test . "<br>";
foreach($test->name as $test1) {
echo $test1 . "<br>";
foreach($test1->value as $test2) {
echo $test2 . "<br>";
}
}
}
*/
/*
foreach($myObj->result as $test) {
if (($test->name) == "Units") {
// grab the value that corresponds to the name
$units = $test->name;
if (($units->name) == "Components") {
$components = $units->name;
print_r($components);
}
}
}
*/
I can access what I need directly, by saying:
print_r($myObj->result[1]->value[0][5]->value[0][1]->name);
print_r($myObj->result[1]->value[0][5]->value[0][1]->value);
but the location of the value may vary, so I need to find the names of the objects by looping
Can anyone provide a better approach using objects (or possibly even associative arrays)?
UPDATED TO INCLUDE SNIPPET OF ORIGINAL JSON (before decode)
string(21420) "{
"info": {
.
.
.
},
"stuff": [{
"name":
"type":
.
.
.
}],
"result": [
{
"name":
"value":
"description":
},
{
"name": "Units",
"value": [
[
{
"name":
"value":
"description":
},
.
.
.
{
"name": "Components",
"value": [
[
{
"name":
"value":
"description":
},
{
"name": "myKey",
"value": "12345678",
"description":
},
.
.
.
] (end inner Components value)
] (end outer Components value)
] (end inner Units value)
] (end outer Units value)
} (end results Units)
] (end result)
} (end opening)
It feels like you need some recursive function (a function that calls itself until it finds the the result) to find the value within the nested array.
Take a look at Recursive array_search
Of course you will have to change the function in that question, but I have similar issue once and it was very userful.
Below is the code for encoding and decoding. hope this helps you
//Encoding
//Array Values
$a1=array("name"=>"abc", "value"=>"def", "description"=>"ghi");
$a2=array("name"=>"jkl", "value"=>"mno", "description"=>"pqr");
$a3=array("name"=>"stu", "value"=>"wxy", "description"=>"zab");
//Array of Value Arrays
$info=array($a1, $a2, $a3);
$result=array($a1, $a2, $a3);
$stuff=array($a1, $a2, $a3);
//The Main Enclosed Array
$main=json_encode(array("info"=>$info, "result"=>$result, "stuff"=>$stuff));
//Decoding
//Fetching the name from result's $a1 array
$main_array=json_decode($main);
echo $main_array->result[1]->name; //Displays jkl

JSON decode only one data php

I have JSON data:
[
{
"title": "red",
},
{
"title": "blue",
},
{
"title": "yellow",
},
]
I want to get only first data, red.
I try with this
...
$json_output=curl_exec($ch);
$mydata = json_decode($json_output);
$result = $mydata->title;
echo $result[1];
and
$result = $mydata->title[1];
but dont work.
How i can get only first "title" data from this json?
$json_output=curl_exec($ch);
$mydata = json_decode($json_output);
$result = $mydata[0]->title;
echo $result;
According to PHP's manual, json_decode returns the value encoded in JSON in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->title;
// Output: red
?>
When 2nd parameter is TRUE, returned objects will be converted into associative arrays.
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output, TRUE);
var_dump($mydata);
/* Ouput:
array(3) {
[0]=>
array(1) {
["title"]=>
string(3) "red"
}
[1]=>
array(1) {
["title"]=>
string(4) "blue"
}
[2]=>
array(1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]['title'];
// Output: red
?>
On a side note, accessing elements within an object that contain any character not allowed under PHP's naming convention can be done by wrapping the index with a curly bracket.
<?php
$json_output = '[{ "h1-title": "red" }, { "h1-title": "blue" }, { "h1-title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["h1-title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["h1-title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["h1-title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->{'h1-title'};
// Output: red
?>
First of all your JSON is not valid. You can use this validator to check if your JSON is valid. It should look like the following:
[
{
"title": "red"
},
{
"title": "blue"
},
{
"title": "yellow"
}
]
There are two ways of accessing the JSON object:
Array of objects:
$mydata = json_decode($json_output);
$title = $mydata[0]->title; // red
Associative array:
$mydata = json_decode($json_output, true);
$title = $mydata[0]['title']; // red
See json_decode() for more information.

Can't get JSON string to parse into an array

I'm using the following PHP code to return a json string:
$itemURL = 'http://***.***.***/search?tag=Football&affiliate_id=&max_results=3';
$response = file_get_contents($itemURL);//curl_exec($curlHandle);
echo $response;
$response = array($response);
echo $response[0];
I get a json string that looks something like this:
[
{
"ID": "123",
"Description": "Champion Football Navy T-shirt",
"HighPrice": 16.99,
"LowPrice": 16.99,
"SalePrice": null,
"OnSale": false,
"URL": "http://www.mystore.com/itemDescription",
"ImageURL": "http://www.mystore.com/mainstore/045.jpg",
"LargeImageURL": "http://www.mystore.com/mainstore/045.jpg",
"ThumbnailImageURL": "http://www.mystore.com/mainstore/045.jpg",
"MiniImageURL": "http://www.mystore.com/mainstore/045.jpg",
"AffiliateID": ""
},
{
"ID": "23",
"Description": "Champion Football Navy T-shirt XL",
"HighPrice": 16.99,
"LowPrice": 16.99,
"SalePrice": null,
"OnSale": false,
"URL": "http://www.mystore.com/itemDescription",
"ImageURL": "http://www.mystore.com/mainstore/045.jpg",
"LargeImageURL": "http://www.mystore.com/mainstore/045.jpg",
"ThumbnailImageURL": "http://www.mystore.com/mainstore/045.jpg",
"MiniImageURL": "http://www.mystore.com/mainstore/045.jpg",
"AffiliateID": ""
}
]
However when I echo $response[0] I get the entire string. If I use json_decode or encode I get a string but with quotes around it. I can't figure out how to cast this dang thing so it operates as an array of objects that I can then iterate through. Thanks for any help in advance
Try this...
$itemURL = 'http://***.***.***/search?tag=Football&affiliate_id=&max_results=3';
$response = file_get_contents($itemURL);//curl_exec($curlHandle);
$response = json_decode($response);
You'll get an object like...
array(2) {
[0]=>
object(stdClass)#1 (12) {
["ID"]=>
string(3) "123"
["Description"]=>
string(30) "Champion Football Navy T-shirt"
["HighPrice"]=>
float(16.99)
["LowPrice"]=>
float(16.99)
["SalePrice"]=>
NULL
["OnSale"]=>
bool(false)
["URL"]=>
string(38) "http://www.mystore.com/itemDescription"
["ImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["LargeImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["ThumbnailImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["MiniImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["AffiliateID"]=>
string(0) ""
}
[1]=>
object(stdClass)#2 (12) {
["ID"]=>
string(2) "23"
["Description"]=>
string(33) "Champion Football Navy T-shirt XL"
["HighPrice"]=>
float(16.99)
["LowPrice"]=>
float(16.99)
["SalePrice"]=>
NULL
["OnSale"]=>
bool(false)
["URL"]=>
string(38) "http://www.mystore.com/itemDescription"
["ImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["LargeImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["ThumbnailImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["MiniImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["AffiliateID"]=>
string(0) ""
}
}
And then you can access your JSON objects using $response[0], $response[1], etc... Using the specific name of the field like $response[0]->AffiliateID for istance.
you need to call the property you are looking for
IE:
echo response[0].ID; //getting the 1st item in the response array then access the "ID" property of the json object.
The json response is a dynamic object that allows you to interact with all the properties as though you created the object from scratch.
The values inside the [{... and the ... }] are the object values.
so...
var json = '{"ID" : 1, "Prop1" : "Value1", Prop2 : "Value2" }';
can be parsed using jQuery's parseJSON method
var obj= jQuery.parseJSON(json);
echo obj.ID; //1
echo obj.Prop1; //Value
echo obj.Prop2; //Value2
When you have the [... and ...] around the { and } you know this object is an array and needs to be treated accordingly.
Hope this helps.
wm
if (mysql_num_rows($result) > 0) {
$response["events"] = array();
while ($row = mysql_fetch_array($result)) {
$tmparr = array();
$tmparr["uid"] = $row["uid"];
$tmparr["date"] = $row["date"];
$tmparr["hours"] = $row["hours"];
$tmparr["store_name"] = $row["store_name"];
$tmparr["event_information"] = $row["event_information"];
$tmparr["event_type"] = $row["event_type"];
$tmparr["Phone"] = $row["Phone"];
$tmparr["price"] = $row["price"];
$tmparr["address"] = $row["address"];
$tmparr["image_url"] = $row["image_url"];
$tmparr["created_at"] = $row["created_at"];
$tmparr["updated_at"] = $row["updated_at"];
array_push($response["events"], $tmparr);
}
$response["success"] = 1;
echo json_encode($response);
I can't understand what you are trying to do but This is the way that i use in order to return an array of rows of data from a sql query ($result). I hope this helps you

json Problems to echo, arrays

I am working on a script, that will use steam api, and i selected to use json for the response format.
So i have used var_dump with and without jason_decode() and it appears to be ok.
But can't manage to print it out, or echo it.
Script that gets the json data
<?php
$id = $_GET['SteamId'];
$get = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=API_KEY_REMOVED_FOR_SECURITY&steamids=$id",true);
$data = json_decode($get);
//var_dump($data);
echo $data->realname;
?>
So, that i get using the var_dump with json_decode is this.
object(stdClass)#1 (1) { ["response"]=> object(stdClass)#2 (1) { ["players"]=> array(1) { [0]=> object(stdClass)#3 (15) { ["steamid"]=> string(17) "76561198053511970" ["communityvisibilitystate"]=> int(3) ["profilestate"]=> int(1) ["personaname"]=> string(9) "Undefined" ["lastlogoff"]=> int(1340978067) ["profileurl"]=> string(41) "http://steamcommunity.com/id/Heisteknikk/" ["avatar"]=> string(114) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd.jpg" ["avatarmedium"]=> string(121) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd_medium.jpg" ["avatarfull"]=> string(119) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd_full.jpg" ["personastate"]=> int(1) ["realname"]=> string(7) "Andreas" ["primaryclanid"]=> string(18) "103582791430704052" ["timecreated"]=> int(1322427688) ["loccountrycode"]=> string(2) "NO" ["locstatecode"]=> string(2) "09" } } } }
And the raw data from the json.
{
"response": {
"players": [
{
"steamid": "76561198053511970",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "Undefined",
"lastlogoff": 1340978067,
"profileurl": "http:\/\/steamcommunity.com\/id\/Heisteknikk\/",
"avatar": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd.jpg",
"avatarmedium": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd_medium.jpg",
"avatarfull": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd_full.jpg",
"personastate": 1,
"realname": "Andreas",
"primaryclanid": "103582791430704052",
"timecreated": 1322427688,
"loccountrycode": "NO",
"locstatecode": "09"
}
]
}
}
I've been searching around on google about printing the json using "echo $data->realname;".
So i don't know what i did wrong, so it canno't echo the data.
Intro
Hey there, this is a REALLY old question, but since there's no answer here.
You do have it right when it comes to decoding the JSON PHP has the built-in function json_decode which can easily decode the function for you:
$json = '{...}';
$obj = json_decode($json, [ASSOC_ARRAY = FALSE]);
The second Param you can set to bool for an associative array which would change mentions from:
$obj->response;
To
$obj['response'];
Response
Now you say you need the realname from the players, that would be as simple as getting it via the player's position in the array, or just looping through the array:
echo $obj->response->players[0]->realname; // Andreas
Or if you have multiple users:
for( $i = 0; $i < count($obj->response->players); $i++ ) {
echo $obj->response->players[$i]->realname;
}
Which would display all of the realname(s)

Categories