how to access elements in a nested array in php - php

When I run following code:
$json2=json_decode($output, true);
echo "<pre>";
echo json_encode($json2, JSON_PRETTY_PRINT);
echo "</pre>";
I get output as following:
[
{
"stream": "live\/cm1",
"size": 1120438999,
"duration": 16233,
"periods": 7,
"path": "\/var\/cache\/nimble\/dvr\/live\/cm1",
"space_available": 212516282368,
"vcodec": "avc1.4d001f",
"resolution": "1280x720",
"bandwidth": 552176,
"timeline": [
{
"start": 1477757618,
"duration": 535
},
{
"start": 1477758226,
"duration": 703
},
{
"start": 1477760431,
"duration": 14295
},
{
"start": 1477829472,
"duration": 559
},
{
"start": 1477879433,
"duration": 40
},
{
"start": 1477881429,
"duration": 79
},
{
"start": 1477881925,
"duration": 22
}
]
},
{
"stream": "live\/cm10",
"size": 1790211828,
"duration": 33976,
"periods": 23,
"path": "\/var\/cache\/nimble\/dvr\/live\/cm10",
"space_available": 212516282368,
"vcodec": "avc1.4d001f",
"resolution": "1280x720",
"bandwidth": 421520,
"timeline": [
{
"start": 1477757606,
"duration": 193
},
{
"start": 1477757817,
"duration": 336
},
{
"start": 1477758226,
"duration": 703
},
{
"start": 1477759027,
"duration": 1378
},
{
"start": 1477760460,
"duration": 14273
},
{
"start": 1477829464,
"duration": 1235
},
{
"start": 1477878029,
"duration": 469
},
{
"start": 1477882600,
"duration": 1260
},
{
"start": 1477883914,
"duration": 208
},
{
"start": 1477911214,
"duration": 1528
},
{
"start": 1477913185,
"duration": 185
},
{
"start": 1477913546,
"duration": 759
},
{
"start": 1477915819,
"duration": 68
},
{
"start": 1478782219,
"duration": 69
},
{
"start": 1478782375,
"duration": 76
},
{
"start": 1478812920,
"duration": 659
},
{
"start": 1478911726,
"duration": 2334
},
{
"start": 1478914138,
"duration": 5
},
{
"start": 1478914233,
"duration": 2872
},
{
"start": 1478917165,
"duration": 1133
},
{
"start": 1478976623,
"duration": 224
},
{
"start": 1478981537,
"duration": 3658
},
{
"start": 1479065575,
"duration": 351
}
]
},
{
"stream": "live\/cm2",
"size": 1320002727,
"duration": 20809,
"periods": 13,
...........
}]
The question I have is how do I access various elements here including how many total sets are there and in each set access a particular object.
Thanks for your help in advance.

Why are you decoding the output and after that you are encoding it again? Look what json_decode does: http://php.net/manual/de/function.json-decode.php
The decoding of your output seems to work well.
So just do the following instead:
$json2=json_decode($output, true);
echo "<pre>";
var_dump($json2);
echo "</pre>";
You will probably get an PHP array containing objects. On this array you can apply anything which is possible with arrays in PHP. You can use count() for instance to count the number of results in the array.
http://php.net/manual/en/language.types.array.php

$json2 is a associative array, access is done using $json[0]["stream"] (for example).
To access all elements, try
foreach( $json2 as $item ) {
echo $item["stream"] . " has a size of " . $item["size"] . " bytes";
foreach( $item["timeline"] as $timeline ) {
//access the timeline-elements (in the case you actually need those)
echo $timeline["start"];
}
}
(See also Parsing JSON object in PHP using json_decode)

Related

how to print a specific json key in php?

Here is my PHP code:
<?php
session_start();
include"smsciniz/vendor/autoload.php";
include"smsciniz/baglan.php";
//$insert = $DB->query("INSERT INTO sc_ulke(ulke_isim) VALUES(?)", array($_POST["ulke_isim"]));
$ulke = $DB->query("SELECT * FROM sc_ulke");
foreach ($ulke as $value) {
$url = file_get_contents("https://5sim.net/v1/guest/products/".trim($value["ulke_isim"])."/any");
$json = json_decode($url,true);
echo $json;
}
?>
And here is my JSON data:
"1688": {
"Category": "activation",
"Qty": 2000,
"Price": 14.83
},
"1xbet": {
"Category": "activation",
"Qty": 11413,
"Price": 19
},
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
"888casino": {
"Category": "activation",
"Qty": 4109,
"Price": 5
},
"99app": {
"Category": "activation",
"Qty": 5437,
"Price": 5
},
I want to print the area I marked but I don't know how to do.
I would be very happy if you could help me with an example, thank you in advance
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
We can iterate and find by particular key and print result using json_encode with JSON_PRETTY_PRINT
function findObjByKey($res, $keyToFind){
foreach ($res as $key => $value) {
if($key == $keyToFind) {
return $value;
}
}
return NULL;
}
$json = json_decode('
{"1688": {
"Category": "activation",
"Qty": 2000,
"Price": 14.83
},
"1xbet": {
"Category": "activation",
"Qty": 11413,
"Price": 19
},
"32red": {
"Category": "activation",
"Qty": 4113,
"Price": 7
},
"888casino": {
"Category": "activation",
"Qty": 4109,
"Price": 5
},
"99app": {
"Category": "activation",
"Qty": 5437,
"Price": 5
}}'
);
$res = findObjByKey($json, '32red');
$prittyPrint= json_encode($res, JSON_PRETTY_PRINT);
echo "<pre>".$prittyPrint."<pre>";
use json_encode($json['32red']) like this you can access any key in json

Set PHP variable to value in JSON object

I have a PHP file which gets a JSON object called $response. The $response has many values (as shown below) and I want to extract a few includes title and price. I have tried the below code but it doesnt show ANY result (no error, no value!). Thoughts?
Thank you
PHP code:
$data = json_decode($response, true);
echo $data->ItemsResult->Items[0]->ItemInfo->Title->DisplayValue;
$response =
{
"ItemsResult": {
"Items": [{
"ASIN": "B0825SNHP1",
"BrowseNodeInfo": {
"BrowseNodes": [{
"Ancestor": {
"Ancestor": {
"Ancestor": {
"ContextFreeName": "Toys & Games",
"DisplayName": "Toys & Games",
"Id": "165793011"
},
"ContextFreeName": "Toys & Games",
"DisplayName": "Categories",
"Id": "165795011"
},
"ContextFreeName": "Stuffed Animals & Plush Toys",
"DisplayName": "Stuffed Animals & Plush Toys",
"Id": "166461011"
},
"ContextFreeName": "Plush Figure Toys",
"DisplayName": "Plush Figures",
"Id": "11350121011",
"IsRoot": false,
"SalesRank": 1
}],
"WebsiteSalesRank": {
"ContextFreeName": "Toys & Games",
"DisplayName": "Toys & Games",
"SalesRank": 32
}
},
"DetailPageURL": "https://www.amazon.com/dp/B0825SNHP1?tag=tpf0bee-20&linkCode=ogi&th=1&psc=1",
"Images": {
"Primary": {
"Large": {
"Height": 500,
"URL": "https://m.media-amazon.com/images/I/51P8jTxbP2L.jpg",
"Width": 467
},
"Medium": {
"Height": 160,
"URL": "https://m.media-amazon.com/images/I/51P8jTxbP2L._SL160_.jpg",
"Width": 149
},
"Small": {
"Height": 75,
"URL": "https://m.media-amazon.com/images/I/51P8jTxbP2L._SL75_.jpg",
"Width": 70
}
},
"Variants": [{
"Large": {
"Height": 450,
"URL": "https://m.media-amazon.com/images/I/51myKYEuuuL.jpg",
"Width": 500
},
"Medium": {
"Height": 144,
"URL": "https://m.media-amazon.com/images/I/51myKYEuuuL._SL160_.jpg",
"Width": 160
},
"Small": {
"Height": 68,
"URL": "https://m.media-amazon.com/images/I/51myKYEuuuL._SL75_.jpg",
"Width": 75
}
}, {
"Large": {
"Height": 500,
"URL": "https://m.media-amazon.com/images/I/515j0HmJV0L.jpg",
"Width": 500
},
"Medium": {
"Height": 160,
"URL": "https://m.media-amazon.com/images/I/515j0HmJV0L._SL160_.jpg",
"Width": 160
},
"Small": {
"Height": 75,
"URL": "https://m.media-amazon.com/images/I/515j0HmJV0L._SL75_.jpg",
"Width": 75
}
}, {
"Large": {
"Height": 466,
"URL": "https://m.media-amazon.com/images/I/51ARoLKEn5L.jpg",
"Width": 500
},
"Medium": {
"Height": 149,
"URL": "https://m.media-amazon.com/images/I/51ARoLKEn5L._SL160_.jpg",
"Width": 160
},
"Small": {
"Height": 70,
"URL": "https://m.media-amazon.com/images/I/51ARoLKEn5L._SL75_.jpg",
"Width": 75
}
}, {
"Large": {
"Height": 500,
"URL": "https://m.media-amazon.com/images/I/414gFkO4AmL.jpg",
"Width": 446
},
"Medium": {
"Height": 160,
"URL": "https://m.media-amazon.com/images/I/414gFkO4AmL._SL160_.jpg",
"Width": 143
},
"Small": {
"Height": 75,
"URL": "https://m.media-amazon.com/images/I/414gFkO4AmL._SL75_.jpg",
"Width": 67
}
}, {
"Large": {
"Height": 500,
"URL": "https://m.media-amazon.com/images/I/516zb5W2o3L.jpg",
"Width": 476
},
"Medium": {
"Height": 160,
"URL": "https://m.media-amazon.com/images/I/516zb5W2o3L._SL160_.jpg",
"Width": 152
},
"Small": {
"Height": 75,
"URL": "https://m.media-amazon.com/images/I/516zb5W2o3L._SL75_.jpg",
"Width": 71
}
}]
},
"ItemInfo": {
"ByLineInfo": {
"Brand": {
"DisplayValue": "Mattel",
"Label": "Brand",
"Locale": "en_US"
},
"Manufacturer": {
"DisplayValue": "Mattel",
"Label": "Manufacturer",
"Locale": "en_US"
}
},
"Classifications": {
"Binding": {
"DisplayValue": "Accessory",
"Label": "Binding",
"Locale": "en_US"
},
"ProductGroup": {
"DisplayValue": "Toy",
"Label": "ProductGroup",
"Locale": "en_US"
}
},
"ContentInfo": {
"Edition": {
"DisplayValue": "Star Wars Edition",
"Label": "Edition",
"Locale": "en_US"
}
},
"ExternalIds": {
"EANs": {
"DisplayValues": ["0887961938814"],
"Label": "EAN",
"Locale": "en_US"
},
"UPCs": {
"DisplayValues": ["887961938814"],
"Label": "UPC",
"Locale": "en_US"
}
},
"Features": {
"DisplayValues": ["This 11-inch The Child plush toy will capture the hearts of Star Wars fans everywhere", "Inspired by the Disney+ series The Mandalorian, the adorable figure with green skin, big ears and large eyes resembles a baby Yoda but is referred to as The Child.", "The toy plush has a soft body, plus a sturdy base filled with beans, perfect for cuddling or display as a collectible", "The character wears his robes as seen in the show.", "Star Wars fans will love taking on the role of The Mandalorian Bounty Hunter and caring for The Child on their own", "Material Type: Polyester"],
"Label": "Features",
"Locale": "en_US"
},
"ManufactureInfo": {
"ItemPartNumber": {
"DisplayValue": "GWD85",
"Label": "PartNumber",
"Locale": "en_US"
},
"Model": {
"DisplayValue": "GWD85",
"Label": "Model",
"Locale": "en_US"
},
"Warranty": {
"DisplayValue": "No Warranty",
"Label": "Warranty",
"Locale": "en_US"
}
},
"ProductInfo": {
"Color": {
"DisplayValue": "Green",
"Label": "Color",
"Locale": "en_US"
},
"IsAdultProduct": {
"DisplayValue": false,
"Label": "IsAdultProduct",
"Locale": "en_US"
},
"ItemDimensions": {
"Height": {
"DisplayValue": 11.02,
"Label": "Height",
"Locale": "en_US",
"Unit": "Inches"
},
"Length": {
"DisplayValue": 5.98,
"Label": "Length",
"Locale": "en_US",
"Unit": "Inches"
},
"Weight": {
"DisplayValue": 0.220462262,
"Label": "Weight",
"Locale": "en_US",
"Unit": "Pounds"
},
"Width": {
"DisplayValue": 7.99,
"Label": "Width",
"Locale": "en_US",
"Unit": "Inches"
}
},
"ReleaseDate": {
"DisplayValue": "2020-02-12T00:00:01Z",
"Label": "ReleaseDate",
"Locale": "en_US"
},
"Size": {
"DisplayValue": "11 inches",
"Label": "Size",
"Locale": "en_US"
},
"UnitCount": {
"DisplayValue": 1,
"Label": "NumberOfItems",
"Locale": "en_US"
}
},
"Title": {
"DisplayValue": "Mattel Star Wars The Child Plush Toy, 11-Inch Small Yoda-Like Soft Figure from The Mandalorian, Green",
"Label": "Title",
"Locale": "en_US"
}
},
"Offers": {
"Listings": [{
"Availability": {
"Message": "In stock. Usually ships within 4 to 5 days.",
"MinOrderQuantity": 1,
"Type": "Now"
},
"Condition": {
"SubCondition": {
"Value": "New"
},
"Value": "New"
},
"DeliveryInfo": {
"IsAmazonFulfilled": false,
"IsFreeShippingEligible": false,
"IsPrimeEligible": false
},
"Id": "xZd%2BKU9rGH7fWwKPEUHMfhsQHzl3QpAN6kIllBjmOl90egwIXEDSkqIt1nqy2q90nMMKYhKCECzkZugn%2FhS6MNMQ0DeGGHgqoDimWML40ChnAKQi3WGnvzASkBlZn3fOYl%2Fk7qoY%2FkafbujzE4UkOjHO6D2nEkcs",
"IsBuyBoxWinner": false,
"MerchantInfo": {
"DefaultShippingCountry": "US",
"FeedbackCount": 261,
"FeedbackRating": 3.53,
"Id": "A111I7FGCUO8HR",
"Name": "ZDeals"
},
"Price": {
"Amount": 27.58,
"Currency": "USD",
"DisplayAmount": "$27.58"
},
"ProgramEligibility": {
"IsPrimeExclusive": false,
"IsPrimePantry": false
},
"ViolatesMAP": false
}],
"Summaries": [{
"Condition": {
"Value": "Collectible"
},
"HighestPrice": {
"Amount": 68.94,
"Currency": "USD",
"DisplayAmount": "$68.94"
},
"LowestPrice": {
"Amount": 58.99,
"Currency": "USD",
"DisplayAmount": "$58.99"
},
"OfferCount": 2
}, {
"Condition": {
"Value": "New"
},
"HighestPrice": {
"Amount": 58.75,
"Currency": "USD",
"DisplayAmount": "$58.75"
},
"LowestPrice": {
"Amount": 22.48,
"Currency": "USD",
"DisplayAmount": "$22.48"
},
"OfferCount": 224
}]
}
}]
}
}
The second argument of json_decode function enables associative array result. So in your case you can either do
$data = json_decode($response);
echo $data->ItemsResult->Items[0]->ItemInfo->Title->DisplayValue;
or
$data = json_decode($response, true);
echo $data['ItemsResult']['Items'][0]['ItemInfo']['Title']['DisplayValue'];

Access Google Calender JSON using PHP

I'm tiring to get holidays from google api here is my php code. which return json data from google corretcly
$calendar_id = urlencode('japanese.ja#holiday.calendar.google.com');
// ε–εΎ—ζœŸι–“
$start = date("Y-01-01\T00:00:00\Z");
$end = date("Y-12-31\T00:00:00\Z");
$url = 'https://www.googleapis.com/calendar/v3/calendars/en.japanese%23holiday%40group.v.calendar.google.com/events?key=apikeyhere';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
if (!empty($result)) {
$json = json_decode($result);
foreach($json->items as $mydata)
{
foreach($mydata as $values)
{
echo $values->summary . "\n";
echo $values->start. "\n";
}
}
I need to get summery and start from that data but above code show nothing, i tired using various foreach but didn't works. can someone help me please to get summery and start from it, thank you
Here is the part output json from google calender v3
{
"kind": "calendar#events",
"etag": "\"p33sets73qumdi0g\"",
"summary": "Holidays in Japan",
"updated": "2018-02-16T08:53:55.000Z",
"timeZone": "UTC",
"accessRole": "reader",
"defaultReminders": [],
"nextSyncToken": "CMCd1N-HqtkCEAAYAQ==",
"items": [
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20170109_60o30d9l6go30e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzAxMDlfNjBvMzBkOWw2Z28zMGUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Coming of Age Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-01-09"
},
"end": {
"date": "2017-01-10"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20170109_60o30d9l6go30e1g60o30dr564#google.com",
"sequence": 0
},
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20170717_60o30d9lcgo30e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzA3MTdfNjBvMzBkOWxjZ28zMGUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Sea Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-07-17"
},
"end": {
"date": "2017-07-18"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20170717_60o30d9lcgo30e1g60o30dr564#google.com",
"sequence": 0
},
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20170918_60o30d9lcko32e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzA5MThfNjBvMzBkOWxja28zMmUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Respect for the Aged Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-09-18"
},
"end": {
"date": "2017-09-19"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20170918_60o30d9lcko32e1g60o30dr564#google.com",
"sequence": 0
},
{
"kind": "calendar#event",
"etag": "\"2778543254000000\"",
"id": "20171009_60o30d9l6ko30e1g60o30dr564",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=MjAxNzEwMDlfNjBvMzBkOWw2a28zMGUxZzYwbzMwZHI1NjQgZW4uamFwYW5lc2UjaG9saWRheUB2",
"created": "2014-01-09T12:47:07.000Z",
"updated": "2014-01-09T12:47:07.000Z",
"summary": "Sports Day",
"creator": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"organizer": {
"email": "en.japanese#holiday#group.v.calendar.google.com",
"displayName": "Holidays in Japan",
"self": true
},
"start": {
"date": "2017-10-09"
},
"end": {
"date": "2017-10-10"
},
"transparency": "transparent",
"visibility": "public",
"iCalUID": "20171009_60o30d9l6ko30e1g60o30dr564#google.com",
"sequence": 0
}
]
}
**I converted this code from js code which have working json part
data variable is the json out put from google, i just need convert this part to php**
for (item in data.items) {
$("#output").append(
"<hr><h3>" + data.items[item].summary + "<h3>" +
"<h4>" + data.items[item].start.date + "<h4>"
);
}
Your code is almost correct, you just have one foreach loop too many, once you are iterating over the items you can access their properties directly, no need to loop through them.
// Check if we got some results
if (!empty($result)) {
// Parse the results
$json = json_decode($result);
// Iterate over the item property of the resultset
foreach($json->items as $item) {
// Each item is an object,
// 'summary' and 'start' are properties of 'item'
// 'date' is a property of 'start'
echo '<hr><h3>' . $item->summary . '</h3>';
echo '<h4>' . $item->start->date . '</h4>';
}
}
I changed the name of $myData to $item, I feel that it makes the code easier to understand, feel free to update the answer if you want to preserve the name $mydata.

How to echo nested JSON object in php

I'm trying to figure out how to echo the address1 out of the JSON below. I've tried this - echo "$arr->location[1]->address1<br>";, but it returns this error
Catchable fatal error: Object of class stdClass could not be converted to string in /home/benrud/public_html/student/webdesign/2016/02_benrud/tinker/data/index.php on line 202.
echo $arr; returns the JSON below.
{
"photos": [
"https://s3-media2.fl.yelpcdn.com/bphoto/37El1q8mqM_1tKtQugncZQ/o.jpg",
"https://s3-media1.fl.yelpcdn.com/bphoto/GLsNPPz5do-_NJktIQvz6w/o.jpg",
"https://s3-media3.fl.yelpcdn.com/bphoto/Z4rdHERgb10MZgDXnct5lA/o.jpg"
],
"coordinates": {
"latitude": 33.0479031276,
"longitude": -117.256002333
},
"image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/37El1q8mqM_1tKtQugncZQ/o.jpg",
"is_claimed": false,
"id": "oscars-mexican-seafood-encinitas-2",
"review_count": 48,
"rating": 4.5,
"hours": [
{
"hours_type": "REGULAR",
"is_open_now": true,
"open": [
{
"is_overnight": false,
"end": "2100",
"day": 0,
"start": "0800"
},
{
"is_overnight": false,
"end": "2100",
"day": 1,
"start": "0800"
},
{
"is_overnight": false,
"end": "2100",
"day": 2,
"start": "0800"
},
{
"is_overnight": false,
"end": "2100",
"day": 3,
"start": "0800"
},
{
"is_overnight": false,
"end": "2200",
"day": 4,
"start": "0800"
},
{
"is_overnight": false,
"end": "2200",
"day": 5,
"start": "0800"
},
{
"is_overnight": false,
"end": "2100",
"day": 6,
"start": "0800"
}
]
}
],
"display_phone": "(760) 487-5778",
"categories": [
{
"alias": "seafood",
"title": "Seafood"
},
{
"alias": "mexican",
"title": "Mexican"
}
],
"price": "$",
"phone": "+17604875778",
"name": "Oscars Mexican Seafood",
"location": {
"zip_code": "92024",
"address3": null,
"address1": "115 N El Camino Real",
"country": "US",
"city": "Encinitas",
"state": "CA",
"cross_streets": "Via Molena & Encinitas Blvd",
"display_address": [
"115 N El Camino Real",
"Encinitas, CA 92024"
],
"address2": ""
},
"transactions": [],
"url": "https://www.yelp.com/biz/oscars-mexican-seafood-encinitas-2?adjust_creative=YqqOIA_bNY3Qb_A1TRMMUg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm_source=YqqOIA_bNY3Qb_A1TRMMUg",
"is_closed": false
}
Location isn't an array, so I'd imagine just $arr->location->address1.
$arr = json_decode($json, true);
the true parameter makes sure it's an array and not an object
You must first decode then call the key so:
// Decode the JSON STRING
$arr = json_decode($arr, true);
/*
* first argument is the JSON STRING,
* Second sets the flag that the string is a dictionary
* (associative array)
*/
Now it is time to call the element. I put it in a conditional so to prevent errors
if (array_key_exists('address1', $arr['location'])) {
echo $arr['location']['address1'];
}
else {
echo "Array element Not Found. Here is what I have:\n\r";
print_r($arr);
}
This Should return your element's value OR Dump the parsed PHP Array for review so you can edit the if statement to get the correct location.

Parsing JSON array with unknown field names?

So I have this json:
{
"success": true,
"rgInventory": {
"4580331488": {
"id": "4580331488",
"classid": "520025252",
"instanceid": "0",
"amount": "1",
"pos": 1
},
"4566197481": {
"id": "4566197481",
"classid": "1439482117",
"instanceid": "188530139",
"amount": "1",
"pos": 2
},
"4566196610": {
"id": "4566196610",
"classid": "1439484944",
"instanceid": "188530139",
"amount": "1",
"pos": 3
},
"4566097797": {
"id": "4566097797",
"classid": "310776859",
"instanceid": "302028390",
"amount": "1",
" pos": 4
},
"4565915026": {
"id": "4565915026",
"classid": "310776840",
"instanceid": "302028390",
"amount": "1",
" pos": 5
},
"4565415060": {
"id": "4565415060",
"classid": "1439489161",
"instanceid": "188530139",
"amount": "1",
"pos": 6
},
"4565413906": {
"id": "4565413906",
"classid": "1439484334",
"instanceid": "188530139",
"amount": "1",
"pos": 7
},
"4559798755": {
"id": "4559798755",
"classid": "520025252",
"instanceid": "0",
"amount": "1",
"pos": 8
},
"4553954652": {
"id": "4553954652",
"classid": "520025252",
"instanceid": "0",
"amount": "1",
"pos": 9
},
"4553694029": {
"id": "4553694029",
"classid": "991959905",
"instanceid": "0",
"amount": "1",
"pos": 10
},
"4553694015": {
"id": "4553694015",
"classid": "720289133",
"instanceid": "188530170",
"amount": "1",
" pos": 11
},
"4553694006": {
"id": "4553694006",
"classid": "1364486740",
"instanceid": "188530139",
"amount": "1",
"pos": 12
},
"4553693992": {
"id": "4553693992",
"classid": "1309991239",
"instanceid": "188530139",
"amount": "1",
"pos": 13
},
"4553693986": {
"id": "4553693986",
"classid": "310776711",
"instanceid": "302028390",
"amount": "1",
" pos": 14
}
}
I need to get it as an array and parse it. The problem is that this json is from my inventory and as I fetch other people's inventory the field are gonna change, and I can't figure out how to parse it.
So far I'm here:
$link='http://steamcommunity.com/profiles/'.$steamid.'/inventory/json/730/2';
$string = file_get_contents($link);
$obj = json_decode($string, true);
var_dump($obj['rgInventory']);
At this point I can get a result, but i don't know how to go beyond that, I mean, I need to return classid and instance id of each record, but hw can this be done in a JSON like that?
You can use a foreach loop
foreach ($obj['rgInventory'] as $key => $item) {
echo $key; // echo the "unknown" field name
echo $item['classid']; // echo any field value
}

Categories