How to access object inside multidimensional array with json decode in PHP? - php

I'm struggling with accessing elements of arrays. I'm sure it's easy but I always get undefined index errors.
Display Array :
// Get response
$synresponse = curl_exec($chs);
// Decode
$variants = json_decode($synresponse, true);
Returns :
{
"code": 200,
"result": {
"sync_product": {
"id": 118425517,
"external_id": "5d02e1420b4007",
"name": "Women's Crop Top",
"variants": 4,
"synced": 4
},
"sync_variants": [
{
"id": 1335801688,
"external_id": "5d02e1420b4141",
"sync_product_id": 118425517,
"name": "Women's Crop Top - S",
"synced": true,
"variant_id": 8039,
"retail_price": "22.50",
"currency": "USD",
"product": {
"variant_id": 8039,
"product_id": 224,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/224/8039_1550478004.jpg",
"name": "Los Angeles Apparel 2332 Fine Jersey Short Sleeve Cropped T-Shirt /w Tear Away Label (White / S)"
},
"files": [
{
"id": 120674338,
"type": "default",
"hash": "6238a66581153315488397a5788216b2",
"url": null,
"filename": "logo2.png",
"mime_type": "image/png",
"size": 163254,
"width": 1380,
"height": 1380,
"dpi": null,
"status": "ok",
"created": 1560465358,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_preview.png",
"visible": true
},
{
"id": 120686478,
"type": "preview",
"hash": "fa1a4b2f561f28529f4230ba49eca1db",
"url": null,
"filename": "mockup-79b7c377.png",
"mime_type": "image/png",
"size": 113878,
"width": 600,
"height": 600,
"dpi": 43,
"status": "ok",
"created": 1560469826,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png",
"visible": false
}
],
"options": []
},
{
"id": 1335801689,
"external_id": "5d02e1420b41b9",
"sync_product_id": 118425517,
"name": "Women's Crop Top - M",
"synced": true,
"variant_id": 8040,
"retail_price": "22.50",
"currency": "USD",
"product": {
"variant_id": 8040,
"product_id": 224,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/224/8040_1550478002.jpg",
"name": "Los Angeles Apparel 2332 Fine Jersey Short Sleeve Cropped T-Shirt /w Tear Away Label (White / M)"
},
"files": [
{
"id": 120674338,
"type": "default",
"hash": "6238a66581153315488397a5788216b2",
"url": null,
"filename": "logo2.png",
"mime_type": "image/png",
"size": 163254,
"width": 1380,
"height": 1380,
"dpi": null,
"status": "ok",
"created": 1560465358,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_preview.png",
"visible": true
},
{
"id": 120686478,
"type": "preview",
"hash": "fa1a4b2f561f28529f4230ba49eca1db",
"url": null,
"filename": "mockup-79b7c377.png",
"mime_type": "image/png",
"size": 113878,
"width": 600,
"height": 600,
"dpi": 43,
"status": "ok",
"created": 1560469826,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png",
"visible": false
}
],
"options": []
},
{
"id": 1335801690,
"external_id": "5d02e1420b41f3",
"sync_product_id": 118425517,
"name": "Women's Crop Top - L",
"synced": true,
"variant_id": 8041,
"retail_price": "22.50",
"currency": "USD",
"product": {
"variant_id": 8041,
"product_id": 224,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/224/8041_1550478000.jpg",
"name": "Los Angeles Apparel 2332 Fine Jersey Short Sleeve Cropped T-Shirt /w Tear Away Label (White / L)"
},
"files": [
{
"id": 120674338,
"type": "default",
"hash": "6238a66581153315488397a5788216b2",
"url": null,
"filename": "logo2.png",
"mime_type": "image/png",
"size": 163254,
"width": 1380,
"height": 1380,
"dpi": null,
"status": "ok",
"created": 1560465358,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_preview.png",
"visible": true
},
{
"id": 120686478,
"type": "preview",
"hash": "fa1a4b2f561f28529f4230ba49eca1db",
"url": null,
"filename": "mockup-79b7c377.png",
"mime_type": "image/png",
"size": 113878,
"width": 600,
"height": 600,
"dpi": 43,
"status": "ok",
"created": 1560469826,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png",
"visible": false
}
],
"options": []
},
{
"id": 1335801691,
"external_id": "5d02e1420b4238",
"sync_product_id": 118425517,
"name": "Women's Crop Top - XL",
"synced": true,
"variant_id": 8042,
"retail_price": "22.50",
"currency": "USD",
"product": {
"variant_id": 8042,
"product_id": 224,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/224/8042_1550478006.jpg",
"name": "Los Angeles Apparel 2332 Fine Jersey Short Sleeve Cropped T-Shirt /w Tear Away Label (White / XL)"
},
"files": [
{
"id": 120674338,
"type": "default",
"hash": "6238a66581153315488397a5788216b2",
"url": null,
"filename": "logo2.png",
"mime_type": "image/png",
"size": 163254,
"width": 1380,
"height": 1380,
"dpi": null,
"status": "ok",
"created": 1560465358,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/623/6238a66581153315488397a5788216b2_preview.png",
"visible": true
},
{
"id": 120686478,
"type": "preview",
"hash": "fa1a4b2f561f28529f4230ba49eca1db",
"url": null,
"filename": "mockup-79b7c377.png",
"mime_type": "image/png",
"size": 113878,
"width": 600,
"height": 600,
"dpi": 43,
"status": "ok",
"created": 1560469826,
"thumbnail_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_thumb.png",
"preview_url": "https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png",
"visible": false
}
],
"options": []
}
]
},
"extra": []
}
I'm trying to access elements from files like this :
foreach($variants['result'] as $variant){
//access file images
$imgurl = $variant['files']['preview_url'];
echo '<img src="$imgurl">';
echo '<br>';
}
I get errors :
Notice: Undefined index: files
Notice: Undefined index: preview_url
Can someone explain to me what I am not understanding please?

My guess is that, there are multiple images, not sure which one would be desired, it could be any of these:
$variant['files'][1]['preview_url']
or
$variant['files'][0]['preview_url']
Test
$variants = json_decode($variants, true);
$html = '';
foreach ($variants['result']["sync_variants"] as $variant) {
$html .= '<img src="' . $variant['files'][1]['preview_url'] . '"><br>';
}
echo $html;
Output
<img src="https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png"><br>
<img src="https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png"><br>
<img src="https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png"><br>
<img src="https://d1yg28hrivmbqm.cloudfront.net/files/fa1/fa1a4b2f561f28529f4230ba49eca1db_preview.png"><br>

This code should help. Problem was connected with additional sub array.
foreach($variants['result']['sync_variants'] as $variant) {
foreach($variant['files'] as $file) {
//access file images
$imgurl = $file['preview_url'];
echo '<img src="' . $imgurl . '">';
echo '<br>';
}
}
Answer to the comment:
foreach($variants['result']['sync_variants'] as $variant) {
foreach($variant['files'] as $file) {
if ($file['type'] != 'preview') {
continue;
}
//access file images
$imgurl = $file['preview_url'];
echo '<img src="' . $imgurl . '">';
echo '<br>';
}
}

Related

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'];

Is it possible extract and merge a single json object from multiple json files?

Sorry for the confusing title. I am having a bit of an issue here merging some JSON files. I need to merge all the products into one array in a separate file.
I have a directory full of same structured json files. I am using glob to select all files and decode->append-->encode json files into one large file.
Here is my code:
<?php
$files = glob("*.json");
$newDataArray = [];
foreach($files as $file){
$thisData = file_get_contents($file);
$thisDataArray = json_decode($thisData);
$newDataArray[] = $thisDataArray;
}
$newDataJSON = json_encode($newDataArray);
file_put_contents("merged.json",$newDataJSON);
?>
Now, the above code seems to work great but I only want to extract all the products.
Quick example of what I need to achieve.
File1.json
{
"status": true,
"user": {
"username": "sally",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "35vR4hr",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "na1Id4t",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
File2.json
{
"status": true,
"user": {
"username": "Jessica",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "wjiefi94",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
I want the data to be merged like:
merged.json
{
"products": [
{
"id": "wjiefi94",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
I hope this makes sense. I feel like I have hit a dead end here. Any help is greatly appreciated.
would it be possible for you to call an external tool like "jq"? handling json (just like csv), especially with many files, is not something you should be doing manually.
btw, your example does not have commas between products 2 and 3 and 3 and 4.
Your new code on line 5 should probably read like this with the array brackets? Otherwise you are overwriting the contents of the last files:
$thisDataArray[] = json_decode($thisData);
And why are you merging products from Sally and Jessica into the same user? Maybe you can just extract all the products objects into one file?
More of a code review than an answer, hope it helps ;)

Random image generator from Imgur album

I'm looking to create an Apache site using PHP so that each time a person directs to it, it will grab a random image from a previously created Imgur album full of images and display the image onload without ever leaving the website. I am thinking I would need to use the Imgur API to make this sort of thing with php but I don't know where to start. Does anybody know how I may be able to do this?
I made this javascript alternative using arrays but this only fetches images listed in the javascript code, I would like to make use of the Imgur API and automatically fetch all the images' URLs from the Imgur album and randomly pick one to display every time the user loads the webpage.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Random</title>
<script type="text/javascript">
function randomlinks(){
var myrandom=Math.round(Math.random()*263)
var links=new Array()
links[0]="http://i.imgur.com/blablablabla.jpg"
window.location=links[myrandom]
}
</script>
</head>
<body onload="randomlinks()">
</body>
</html>
This is a json returned from an album using the imgur api, you can transform this json into an array within PHP and then use array_rand() to select a random one:
{
"data": {
"id": "lDRB2",
"title": "Imgur Office",
"description": null,
"datetime": 1357856292,
"cover": "24nLu",
"account_url": "Alan",
"account_id": 4,
"privacy": "public",
"layout": "blog",
"views": 13780,
"link": "http://alanbox.imgur.com/a/lDRB2",
"images_count": 11,
"images": [
{
"id": "24nLu",
"title": null,
"description": null,
"datetime": 1357856352,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 855658,
"views": 135772,
"bandwidth": 116174397976,
"link": "http://i.imgur.com/24nLu.jpg"
},
{
"id": "Ziz25",
"title": null,
"description": null,
"datetime": 1357856394,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 919391,
"views": 135493,
"bandwidth": 124571044763,
"link": "http://i.imgur.com/Ziz25.jpg"
},
{
"id": "9tzW6",
"title": null,
"description": null,
"datetime": 1357856385,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 655028,
"views": 135063,
"bandwidth": 88470046764,
"link": "http://i.imgur.com/9tzW6.jpg"
},
{
"id": "dFg5u",
"title": null,
"description": null,
"datetime": 1357856378,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 812738,
"views": 134704,
"bandwidth": 109479059552,
"link": "http://i.imgur.com/dFg5u.jpg"
},
{
"id": "oknLx",
"title": null,
"description": null,
"datetime": 1357856338,
"type": "image/jpeg",
"animated": false,
"width": 1749,
"height": 2332,
"size": 717324,
"views": 32938,
"bandwidth": 23627217912,
"link": "http://i.imgur.com/oknLx.jpg"
},
{
"id": "OL6tC",
"title": null,
"description": null,
"datetime": 1357856321,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 1443262,
"views": 32346,
"bandwidth": 46683752652,
"link": "http://i.imgur.com/OL6tC.jpg"
},
{
"id": "cJ9cm",
"title": null,
"description": null,
"datetime": 1357856330,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 544702,
"views": 31829,
"bandwidth": 17337319958,
"link": "http://i.imgur.com/cJ9cm.jpg"
},
{
"id": "7BtPN",
"title": null,
"description": null,
"datetime": 1357856369,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 844863,
"views": 31257,
"bandwidth": 26407882791,
"link": "http://i.imgur.com/7BtPN.jpg"
},
{
"id": "42ib8",
"title": null,
"description": null,
"datetime": 1357856424,
"type": "image/jpeg",
"animated": false,
"width": 2592,
"height": 1944,
"size": 905073,
"views": 30945,
"bandwidth": 28007483985,
"link": "http://i.imgur.com/42ib8.jpg"
},
{
"id": "BbwIx",
"title": null,
"description": null,
"datetime": 1357856360,
"type": "image/jpeg",
"animated": false,
"width": 1749,
"height": 2332,
"size": 662413,
"views": 30107,
"bandwidth": 19943268191,
"link": "http://i.imgur.com/BbwIx.jpg"
},
{
"id": "x7b91",
"title": null,
"description": null,
"datetime": 1357856406,
"type": "image/jpeg",
"animated": false,
"width": 1944,
"height": 2592,
"size": 618567,
"views": 29259,
"bandwidth": 18098651853,
"link": "http://i.imgur.com/x7b91.jpg"
}
]
},
"success": true,
"status": 200
}
More information in the IMGUR API Documentation
Being $json the string coming from imgur servers, this code will gather a random link:
$array=json_decode($json);
$links = array();
foreach($array->data->images as $img)
$links[]=$img->link;
echo $links[array_rand($links)];

Laravel json response from Controller and use Ajax to render in the View

Im working with Laravel 5.1 and have a small issue.
I am sending a JSON response from Instagram's API for most popular media from my controller and want to grab that response in my view with ajax and show it on page to the user without loading the entire page.
I am trying to grab the username and display it in my view to the user.
Right now nothing happens and the console does not show anything, it is empty.
This is my code:
CONROLLER:
public function PopularPics(City $city){
try{
$jsonData = $city->getMostPopularPics();
return response()->json($jsonData);
}catch(\Exception $ex){
return $ex->getCode();
}
}
VIEW
<ul id="theData">
</ul>
<script>
$(function(){
$("#JRequest").click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "popular",
dataType:"json",
success:function(items){
$.each(items.data,function(i,item){
console.log(item.user.username);
});
}
});
});
});
</script>
INSTAGRAM JSON
{
"data": [{
"type": "image",
"users_in_photo": [],
"filter": "Gotham",
"tags": [],
"comments": { ... },
"caption": {
"created_time": "1296656006",
"text": "ãã¼ãâ¥ã¢ããªå§ãã¦ä½¿ã£ã¦ã¿ãã(^^)",
"from": {
"username": "cocomiin",
"full_name": "",
"type": "user",
"id": "1127272"
},
"id": "26329105"
},
"likes": {
"count": 35,
"data": [{
"username": "mikeyk",
"full_name": "Kevin S",
"id": "4",
"profile_picture": "..."
}, {...subset of likers...}]
},
"link": "http://instagr.am/p/BV5v_/",
"user": {
"username": "cocomiin",
"full_name": "Cocomiin",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1127272_75sq_1296145633.jpg",
"id": "1127272"
},
"created_time": "1296655883",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/01/34d027f155204a1f98dde38649a752ad_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22518783",
"location": null
},
{
"type": "video",
"videos": {
"low_resolution": {
"url": "http://distilleryvesper9-13.ak.instagram.com/090d06dad9cd11e2aa0912313817975d_102.mp4",
"width": 480,
"height": 480
},
"standard_resolution": {
"url": "http://distilleryvesper9-13.ak.instagram.com/090d06dad9cd11e2aa0912313817975d_101.mp4",
"width": 640,
"height": 640
},
"users_in_photo": null,
"filter": "Vesper",
"tags": [],
"comments": {
"data": [{
"created_time": "1279332030",
"text": "Love the sign here",
"from": {
"username": "mikeyk",
"full_name": "Mikey Krieger",
"id": "4",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1242695_75sq_1293915800.jpg"
},
"id": "8"
},
{
"created_time": "1279341004",
"text": "Chilako taco",
"from": {
"username": "kevin",
"full_name": "Kevin S",
"id": "3",
"profile_picture": "..."
},
"id": "3"
}],
"count": 2
},
"caption": null,
"likes": {
"count": 1,
"data": [{
"username": "mikeyk",
"full_name": "Mikeyk",
"id": "4",
"profile_picture": "..."
}]
},
"link": "http://instagr.am/p/D/",
"user": {
"username": "kevin",
"full_name": "Kevin S",
"profile_picture": "...",
"id": "3"
},
"created_time": "1279340983",
"images": {
"low_resolution": {
"url": "http://distilleryimage2.ak.instagram.com/11f75f1cd9cc11e2a0fd22000aa8039a_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage2.ak.instagram.com/11f75f1cd9cc11e2a0fd22000aa8039a_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage2.ak.instagram.com/11f75f1cd9cc11e2a0fd22000aa8039a_7.jpg",
"width": 612,
"height": 612
}
},
"id": "3",
"location": null
},
...]
}

extract data value from nested JSON

I am trying to get some specific fields out of this Json.
fn({
"processingDurationMillis": 454,
"authorisedAPI": true,
"success": true,
"airline": "MH",
"validCreditCards": [
"AX",
"CA",
"VI"
],
"paypal": true,
"outboundOptions": [
{
"optionId": 0,
"flights": [
{
"flightNumber": "0066",
"departureAirport": {
"code": "KUL",
"name": "Kuala Lumpur Intl",
"city": "Kuala Lumpur",
"country": "Malaysia",
"timezone": "Asia/Kuala_Lumpur",
"lat": 2.745578,
"lng": 101.709917,
"terminal": null,
"gate": null
},
"arrivalAirport": {
"code": "ICN",
"name": "Incheon Intl",
"city": "Seoul",
"country": "South Korea",
"timezone": "Asia/Seoul",
"lat": 37.469075,
"lng": 126.450517,
"terminal": null,
"gate": null
},
"marketingAirline": "MH",
"mealIndicator": "M",
"allowedSsrs": {
},
"operatingAirline": null,
"equipment": "333",
"equipmentName": "Airbus A330-300",
"flightRPH": 10101,
"comments": [
"MH CODESHARE WITH KE"
],
"depScheduled": "2015-04-28T23:30:00.000+08:00",
"arrScheduled": "2015-04-29T07:10:00.000+09:00",
"depEstimated": null,
"depActual": null,
"arrEstimated": null,
"arrActual": null,
"eligibleForEticketing": true,
"cabin": "ECONOMY",
"fareMarketingType": "BASIC",
"rbd": "N",
"seatsAvailable": 9,
"durationMinutes": 400,
"minutesToScheduledFlightDeparture": 6486
}
],
"stopOvers": [
],
"fareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "1214.95",
"currencyCode": "MYR"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "68.90",
"taxes": [
{
"code": "MY",
"amount": "65.00",
"currency": "MYR"
},
{
"code": "D8",
"amount": "3.90",
"currency": "MYR"
}
]
}
],
"journeyFare": "1214.95",
"totalTripFare": "1283.90",
"fareCurrency": "MYR"
},
"magicString": "2t2qi8oNXWkrDR75zYDrk9+3wNaJBzHyK1ftoR/VZPVgHO+EFTkh8DMg5WUl1ap7VjwBsnhD2gFxAwBbHhY0+k0lp7BUvSoYSKg6S6u4ZkvbIWMktl+lHgcKl46vht9//2dZVJvH4D7WJvnJTtK5O4TWNrkiTmEdHp55yRmjwWfsgNswOIMXoWrZj3OUJ4DH4POJ8rmfilimvtpBCdxNsqoZDVC9d6/6LiICZ3wHZJ7w/88QuExFV7OsHbc+jI3trRzDCCb6Ns62MGyfsXX6Pz8mJe6gs02UjapVSPa3M9CqLGMCN0xCF28WNbavhSI9jG3cWsQbxGU8rnhmjx00Iw5v2qqjdE/Dx432Qzs4s36SqUjLF7KN9hAJoQuMX3emE4gZ+7ANJ5bDTDEYZlnUZ4iXKykzUptYDyGay0evu1kdCjxPJlgiEtOl3hFMaKC+eoTsjps4RoYy0Z7oD3aP52qCYPdCH+8XTic522UKU1mW9HMjmGxH5zrvYK2rOgzSR2+xH5K3IpXHBAQqWOTEvmirP4qvg5VOPjyO9mIM83I6aY1JAkqo9jYqtEwrGqANdhA9z78EdoyQYKZBXcLsQMKz06fAczwk/WxxIi1ctL8EW+aZYddkbPo7xD6NWc8bJ+ARw5AlS1tirVNcO3mN5jVr/a6qftVuaz/0q83VsX4ztQpgMjDkptbw9Zz6DNLgiLJEzdf7fraoVUyzeth5wucOMzpLBP+ERbD7XFnDSKN8QzG6lLpDK8qy95K5FMmcF4uDq8Y1waTyIN9sS+v50OTbjr7Ebs3uKIxMZFfGUfp7YpDiVyo+2x4La4K7rhHPtoR6iEfVCjnTAUvamQu3qgL3vuSCPPPJiHFbdOrKVlp3kfAxaIcJpX3Z+Twx2cNAhsGHSk2ZazzvP5Pw1EF066VcoDkld9Oe/Qu5cC+DtG2LHhMA7NU8hMD66q9UCsXC6P/mjbKr7hatjHyyklDIKuxxirMpYkukEa73RJlhKmC0fjj4EYcgRy5MtybexuN59KaTeSEFxMGFIkv0zHp5jO/wHUvyypqbxTKFR3VAx6WpmSNg/Iui2uXDhNu/F4zJnYQUW9EyluZEPebFk2Uj455O2+y0UmFe4WnUY+0d92obZNv855/ctA4UC/LQn2s9azqdhDIeUUHuHEn2a4Grb+7l8wuai6ybBmmE62ck+CqMou+A+CUwk71KMkh3ZXf8BdeelW8Ia7r9ja7wKNBklgYo4Q8xOR63QhyCt2BiiR9aOxiDIKiW7bxSFCBga7yIPWx/NZdGjUYTuiJ9KZ7W2dKLhF6XDU5mWOV7XwMRzkyschEnjSzQWGjTTftEIiNI1V1M2bhFwc92JkfVFxwXCg==",
"seatsAvailable": [
9
],
"corporateAccount": false,
"flightCanBeHeld": true,
"durationMinutes": 400,
"gaFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "1214.95",
"currencyCode": "MYR"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "68.90",
"taxes": [
{
"code": "MY",
"amount": "65.00",
"currency": "MYR"
},
{
"code": "D8",
"amount": "3.90",
"currency": "MYR"
}
]
}
],
"journeyFare": "1214.95",
"totalTripFare": "1283.90",
"fareCurrency": "MYR"
},
"adobeFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "336.66",
"currencyCode": "USD"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "19.09",
"taxes": [
{
"code": "MY",
"amount": "18.01",
"currency": "USD"
},
{
"code": "D8",
"amount": "1.08",
"currency": "USD"
}
]
}
],
"journeyFare": "336.66",
"totalTripFare": "355.77",
"fareCurrency": "USD"
},
"userAgentFareDetails": {
"perPassengerJourneyFares": [
{
"passengerType": "ADT",
"fare": "336.66",
"currencyCode": "USD"
}
],
"perPassengerTripTaxes": [
{
"passengerType": "ADT",
"totalTax": "19.09",
"taxes": [
{
"code": "MY",
"amount": "18.01",
"currency": "USD"
},
{
"code": "D8",
"amount": "1.08",
"currency": "USD"
}
]
}
],
"journeyFare": "336.66",
"totalTripFare": "355.77",
"fareCurrency": "USD"
},
"eligibleForeTicketing": true,
"lowestSeatCount": 9,
"directFlight": true
}
],
"departureAirport": {
"code": "KUL",
"name": "Kuala Lumpur Intl",
"city": "Kuala Lumpur",
"country": "Malaysia",
"timezone": "Asia/Kuala_Lumpur",
"lat": 2.745578,
"lng": 101.709917,
"terminal": null,
"gate": null
},
"arrivalAirport": {
"code": "ICN",
"name": "Incheon Intl",
"city": "Seoul",
"country": "South Korea",
"timezone": "Asia/Seoul",
"lat": 37.469075,
"lng": 126.450517,
"terminal": null,
"gate": null
},
"apiRequired": true,
"fareRules": [
{
"id": 50,
"order": 1,
"priority": 0,
"code": "Basic",
"name": "MHbasic",
"value": "Economy Class Fares",
"listFareRules": [
{
"id": 130,
"order": 0,
"code": "",
"name": "Discount level",
"value": "Up to 65%"
},
{
"id": 140,
"order": 1,
"code": "",
"name": "Where to buy",
"value": "All channels"
},
{
"id": 150,
"order": 2,
"code": "",
"name": "Advance purchase",
"value": "Applies"
},
{
"id": 160,
"order": 3,
"code": "",
"name": "Payment",
"value": "Ticket dateline applies"
},
{
"id": 170,
"order": 4,
"code": "",
"name": "Baggage allowance",
"value": "2pc/30kg"
},
{
"id": 180,
"order": 5,
"code": "",
"name": "Advance seat selection",
"value": "Not allowed"
},
{
"id": 190,
"order": 6,
"code": "",
"name": "Enrich miles",
"value": "Nil"
},
{
"id": 200,
"order": 7,
"code": "",
"name": "Change of booking",
"value": "Not allowed"
},
{
"id": 210,
"order": 8,
"code": "",
"name": "Upgrade",
"value": "Not allowed"
},
{
"id": 220,
"order": 9,
"code": "",
"name": "Stand by at the airport",
"value": "For a fee"
},
{
"id": 220,
"order": 10,
"code": "",
"name": "No show",
"value": "Penalty applies"
},
{
"id": 230,
"order": 11,
"code": "",
"name": "Refund",
"value": "For a fee"
}
],
"listFareNotes": [
{
"id": 10,
"order": 0,
"code": "",
"name": "Important Notice",
"value": ""
},
{
"id": 15,
"order": 1,
"code": "",
"name": "",
"value": ""
},
{
"id": 20,
"order": 2,
"code": "",
"name": "1.",
"value": "Generic attributes shown only applies to MH operated flights. MH3000-3999, MH5200-5999 and MH9000-9999 Series flights are subject to their own rules. Please contact MH Call Center or ticket offices for actual fare rules."
},
{
"id": 30,
"order": 3,
"code": "",
"name": "2.",
"value": "For transpacific and transatlantic flights, the following baggage allowances apply: Economy - 2 pieces (23kg each piece), First and Business - 2 pieces (32kg each piece)."
},
{
"id": 50,
"order": 5,
"code": "",
"name": "3.",
"value": "Upgrade, standby at the airport and refund fees for specific routes can be obtained from subsequent booking pages."
},
{
"id": 60,
"order": 6,
"code": "",
"name": "4.",
"value": "Standby at the airport denotes the same day for an earlier flight."
},
{
"id": 70,
"order": 7,
"code": "",
"name": "5.",
"value": "Fare rules shown are indicative only. Please call our Contact Center to check the detailed fare rules."
},
{
"id": 80,
"order": 8,
"code": "",
"name": "",
"value": "Should there be any discrepancy between the above information and the terms and conditions (T&C) published in the fare rules, then the T&C in the fare rules shall prevail."
}
]
}
],
"Errors": [
],
"Warnings": [
]
})
i want extract flight number, depScheduled, arrScheduled and journey fare from the above json.
here are my code:
$json2 = json_decode($json,true);
$result= array();
foreach ($json2['outboundOptions']['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
print_r($result);
The code above return me a error, "Invalid argument supplied for foreach()".I searched around, but still have not found the solution yet..
It is giving you that error because outboundOptions is an array of objects. What you want is to access the first object:
foreach ($json2['outboundOptions'][0]['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
Also, remove the trailing comma (,) from your ] at the end as that causes invalid json.
You can check if your json is valid by going to jsonlint.com
Working Example
Update as per your comment
To get all the flights, change your foreach loop to this:
foreach ($json3['outboundOptions'] as $flight) {
foreach($flight['flights'] as $theentity) {
$result[] = $theentity['flightNumber'];
}
}
Example
remove the trailing ',' near the very end of your json.
change your code, add a [0] before ['flights']
$json2 = json_decode($json,TRUE);
$result= array();
foreach ($json2['outboundOptions'][0]['flights']as $theentity) {
$result[] = $theentity['flightNumber'];
}
print_r($result);

Categories