PHP - Getting array element from Json - php

I'm working with the JSON here: http://steamcommunity.com/id/mitch8910/inventory/json/730/2/
I'm trying to get the tags[{"name":""}] part of it. For example, I would want the 'container', from '"name":"Container"'
This is my code here:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[1];
}
tags[] is an array, though I did tags[1], I don't awlays want the '1'th element because the position of "name" could change in the array for different elements, I just did this to test, but I got an error. I have tried multiple ways with multiple errors, that why I'm not posting all the error code.

The simplest way may be to do an extra loop to grab all the name elements:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
foreach($mydata->tags as $tag) {
echo $tag->name;
}
}
or to get the first name of each tag group:
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[0]->name;
}

I updated the whole answer:
$json = json_decode($data, true);
if (isset($json['rgDescriptions']) && is_array($json['rgDescriptions'])){
foreach ($json['rgDescriptions'] as $array_no => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'])){
echo "{$array_no}::::";
foreach ($json['rgDescriptions'][$array_no]['tags'] as $k => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'][$k]['name'])){
echo "{$json['rgDescriptions'][$array_no]['tags'][$k]['name']},";
}
}
echo "<br />";
}
}
}

Related

creating one loop for parsing json data

So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.

How to echo value of "id"?

{"2b44928ae11fb9384c4cf38708677c48":{
"id":"115",
"qty":3,
"option":"{\"color\":{\"title\":\"Color\",
\"value\":\"\"
}
}",
"price":150,
"name":"Nightwear",
"shipping":"5",
"tax":3,
"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg",
"coupon":"",
"rowid":"2b44928ae11fb9384c4cf38708677c48",
"subtotal":450
}
}
Hello everyone,
This is my array and I want to echo value of only "id" i.e. I want to get value as '115' of key- "id". Please guide me how to make a foreach for this one? I have tried lots of variations but none worked :(
TIA :)
UPDATE-
I have tried this but did not get any result:
foreach($res as $k=>$t)
{
echo $t["product_details"]["id"];
}
Before you can use the JSON as an array you need to convert it first. use json_decode() for that.
<?php
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true);
foreach($array as $key=>$value){
echo $value['id'];
}
?>
Assuming you have an array of objects like you provided in your post, I have put your object in an array for testing
<?php
$json = '[{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}},'.
'{"2b44928ae11fb9384c4cf38708677c48":{"id":"116","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}]';
$json = json_decode($json);
foreach ($json as $object){
$propsArray = get_object_vars($object);
reset($propsArray);
echo $object->{key($propsArray)}->id . "<br>\n";
}
exit;
this outputs
115
116
try a live demo (https://eval.in/836364)
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true); // convert json string to array
$result = array_column($array, 'id'); // find matching array key and return values in array
foreach ($result as $value) { // echo each value with foreach loop
echo $id . '<br>';
}

Printing json data

I have this json "https://www.decodethis.com/webservices/decodes/1Fmzu64p5yzb76700/aYcBzLfMCRs_JScq_sZt/0.json"
and I decode it with $data = json_decode($json, true);
But when I try to print the Vehicle part foreach($data['vehicle'][0] as $p)
{echo $p;}
the system prints"Invalid argument supplied for foreach()" and "Undefined index".
I'm a newbie, so forgive me.
Edit:This worked very well foreach ($data['decode']['vehicle'][0] as $p) echo $p;, but now I wonder if I can know the key or index of the element $p on every loop, as example "body>driveline>engine>id"...
the path is like these;
foreach ($data['decode']['vehicle'][0] as $p) echo $p;
You may want to to use:
$json = file_get_contents("https://www.decodethis.com/webservices/decodes/1Fmzu64p5yzb76700/aYcBzLfMCRs_JScq_sZt/0.json");
$obj = json_decode($json, true);
foreach($obj["decode"]["vehicle"] as $vehicle )
{
echo $vehicle['body'];
echo $vehicle['engine'];
# etc...
}
For accessing output in json file there is decode as root key. So first access decode key then after use vehicle information.
Below is code for that:
$data = json_decode($json, true);
$json = $data["decode"]["vehicle"][0];
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}

JSON decode in php web programming

I am facing a problem in php using CURL. I made a https request and I got response in multidimesional array.
[{
"id":"22622",
"name":"",
"email":"ffv7678#gmail.com",
"mobileno":"",
"birth_dt":"",
"marital_status":"",
"gender":"",
"educationid":"0",
"occupationid":"0",
"industryid":"0",
"incomeid":"",
"city":"0",
"state":"0",
"country":"0",
"postcode":"",
"deviceid":"805086099499488",
"regid":"",
"device_type":null,
"userstatus":"0",
"refcode":"D1219C92",
"new_user":"0",
"device_token":""
}]
Now I want to decode it and save the value of "id" in a variable.
$result=curl_exec($ch);
$books = json_decode($result, true);
echo ($books[0]['id']);
I tried the above code, but failed.
$books = json_decode($result, true);
foreach ($books as $book)
{
//$book carries info of books;
$id = $book['id'];
///... You can define other variables here
}
You need to use foreach() loop for this.
foreach ($a[0] as $key => $value) {
echo $key."<br>".$value;
if($key == 'id'){
$id = $value;
}
}
echo $id;
Also, if you just want to assign the value of id to another variable, you can just right
...
$no = $a[0]->id;
echo $no
...
instead of the foreach loop.

PHP - How to Loop through JSON array with fields starting with "$"

I have been trying to workout how to loop through and output the contents of a json file where field names start with "$" and keep getting an Undefined variable error message
Here is an example of the json file example (taken from https://mixpanel.com/help/reference/webhooks):
[
{
"$distinct_id":"13b20239a29335",
"$properties":{
"$region":"California",
"$email":"harry.q.bovik#andrew.cmu.edu",
"$last_name":"Bovik",
"$created":"2012-11-20T15:26:16",
"$country_code":"US",
"$first_name":"Harry",
"Referring Domain":"news.ycombinator.com",
"$city":"Los Angeles",
"Last Seen":"2012-11-20T15:26:17",
"Referring URL":"http://news.ycombinator.com/",
"$last_seen":"2012-11-20T15:26:19",
}
},
{
"$distinct_id":"13a00df8730412",
"$properties":{
"$region":"California",
"$email":"anna.lytics#mixpanel.com",
"$last_name":"Lytics",
"$created":"2012-11-20T15:25:38",
"$country_code":"US",
"$first_name":"Anna",
"Referring Domain":"www.quora.com",
"$city":"Mountain View",
"Last Seen":"2012-11-20T15:25:39",
"Referring URL":"http://www.quora.com/What-...",
"$last_seen":"2012-11-20T15:25:42",
}
}
]
I am testing with a static string just to try and get things working. Here is my test code...
<?php
$input = '[{"$distinct_id":"13b20239a29335","$properties":"dddd"}]';
$jsonObj = json_decode($input, true);
foreach ($jsonObj as $item) {
foreach ($item as $rec) {
echo '<br>';
$my_id = $rec->$distinct_id;
echo($my_id);
$my_id = $rec->$properties;
echo($my_id);
}
echo '<br>';
}
?>
Any help would be appreciated.
Noob!
UPDATE: Musa gave this example which works for the single level json:
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
$my_id = $item->{'$properties'};
echo($my_id);
echo '<br>';
}
How can this then be adapted to read and output all elements of the bigger multi-level json file?
Use Curly bracket notation
$object->{'$property'};
Edit
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
foreach ($item->{'$properties'} as $my_prop => $value){
echo("$my_prop => $value");
}
echo '<br>';
}
http://codepad.org/1cudZqlu
With the nested loop you're iterating the properties $distinct_id and $properties so $rec is actually a string and not an object.
Also your json is invalid as it has trailing , in the $properties field.

Categories