how to access 2nd array in an associative array - php

I have an array returned from a json, I can access the values from one part of the array, but I can't access the values from another part of the array
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
I get the first three fine but the last one for stores returns the error
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Notice: Undefined property: stdClass::$stores in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
Notice: Trying to get property 'store_name' of non-object in
C:\xampp\htdocs\customs\production\test-barcodelookup.php on line 20
$ch = curl_init(); // Use only one cURL connection for multiple queries
$data = get_data($url, $ch);
$response = array();
$response = json_decode($data);
echo '<strong>Barcode Number:</strong> ' . $response->products[0]->barcode_number . '<br><br>';
echo '<strong>Product Name:</strong> ' . $response->products[0]->product_name . '<br><br>';
echo '<strong>Description:</strong> ' . $response->products[0]->description . '<br><br>';
echo '<strong>Description:</strong> ' . $response->stores[0]->store_name . '<br><br>';
echo '<strong>Entire Response:</strong><pre>';
print_r($response);
echo '</pre>';
function get_data($url, $ch) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Below is the array returned
Entire Response:
stdClass Object
(
[products] => Array
(
[0] => stdClass Object
(
[barcode_number] => 077341125112
[barcode_type] => UPC
[barcode_formats] => UPC 077341125112, EAN 0077341125112
[mpn] => 0007734112511
[model] => 89960w
[asin] =>
[product_name] => Custom Accessories 89960W E-Tek Butane Torch
[title] =>
[category] => Hardware > Tools > Hardware Torches
[manufacturer] =>
[brand] => Etek
[label] =>
[author] =>
[publisher] =>
[artist] =>
[actor] =>
[director] =>
[studio] =>
[genre] =>
[audience_rating] =>
[ingredients] =>
[nutrition_facts] =>
[color] =>
[format] =>
[package_quantity] =>
[size] =>
[length] =>
[width] =>
[height] =>
[weight] =>
[release_date] =>
[description] => Butane Torch, 89960W is ideal for your home garage or your car. Can be used for quick repairs.
[features] => Array
(
)
[images] => Array
(
[0] => https://images.barcodelookup.com/3001/30014169-1.jpg
)
[stores] => Array
(
[0] => stdClass Object
(
[store_name] => Wal-Mart.com USA, LLC
[store_price] => 14.97
[product_url] => http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
[currency_code] => USD
[currency_symbol] => $
)
[1] => stdClass Object
(
[store_name] => Jet.com
[store_price] => 14.20
[product_url] => http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2
[currency_code] => USD
[currency_symbol] => $
)
)
[reviews] => Array
(
[0] => stdClass Object
(
[name] => Ken Weber
[rating] => 5
[title] => Torch Performance
[review] => I didnt know how good this torch was until I used it and its very nice for the money. The electronic ignition fires the butane evertime. Nice feel to it. Has a trigger lock down for extended usage time. GOOD PRODUCT.
[datetime] => 2015-12-29 11:27:34
)
)
)
)
)
I am trying to access the images array and echo it out and the information from the stores array and echo it. I can get the information from the products array. but I can't figure out how to get the others
This is what I am trying to achieve
Barcode Number: 077341125112
Product Name: Custom Accessories 89960W E-Tek Butane Torch
Description: Butane Torch, 89960W is ideal for your home garage or
your car. Can be used for quick repairs.
Display Image of product.
Stores:
store_name: Wal-Mart.com USA, LLC store_price: 14.97 product_url:
http://www.walmart.com/ip/Custom-Accessories-89960W-E-Tek-Butane-Torch/29029306
store_name: Jet.com store_price: 14.20 product_url:
http://jet.com/product/detail/a43035df304c4551b45f62262402f9f2

When you format the data, it shows that the stores data is under each product, so you would need to display it as...
$response->products[0]->stores[0]->store_name
You would also probably need to use a foreach() to display all the details, both with products and the stores for each product.
foreach ( $response->products[0]->stores as $store ) {
// Echo out the details
echo $store->store_name;
}

Side-step: I think the easiest way to go about this process is using
json_decode($json, true);
This makes everything an associative array.
Here is the manual for the json_decode internal function.
Step-back:
$response->products[0]->stores[0]->store_name

Related

php - Parse Goole Books PI JSON [duplicate]

This question already has answers here:
Using Google Books API
(2 answers)
Closed 5 years ago.
I have written a PHP code to parse the data pobidd by GoogleBooks API
<?php
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode($json, true);
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["subtitle"];
echo $obj["volumeInfo"]["authors"];
echo $obj["volumeInfo"]["printType"];
echo $obj["volumeInfo"]["pageCount"];
echo $obj["volumeInfo"]["publisher"];
echo $obj["volumeInfo"]["publishedDate"];
echo $obj["accessInfo"]["webReaderLink"];
?>
When execute it, I get
Notice: Undefined index: volumeInfo in /storage/ssd3/164/2474164/public_html/dev/fetch/v2.php on line 8
for all the echo strings , so I re-checked all possible sources of problem without solution
You're accessing the array elements in the wrong way. Do var_dump($obj); or echo '<pre>'; print_r($obj); echo '</pre>'; to see the complete array structure. Your echo statements would be like this:
echo $obj['items'][0]["volumeInfo"]["title"] . '<br />';
// echo $obj['items'][0]["volumeInfo"]["subtitle"];
echo $obj['items'][0]["volumeInfo"]["authors"][0] . '<br />';
echo $obj['items'][0]["volumeInfo"]["printType"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["pageCount"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publisher"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publishedDate"] . '<br />';
echo $obj['items'][0]["accessInfo"]["webReaderLink"] . '<br />';
Not sure whether you would be getting subtitle information along with the book details. If so, then please uncomment that line.
To my mind it is far easier to use the object notation for accessing the various properties of the JSON response rather than the clunky array syntax but you need to identify the correct location in the object/array heirarchy before attempting to access the sub-keys of it.
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode( $json );
$items=$obj->items;
foreach( $items as $item ){
/* Main keys */
$vol=$item->volumeInfo;
$sales=$item->saleInfo;
$access=$item->accessInfo;
$info=$item->searchInfo;
/* subkeys */
$title=$vol->title;
$authors=implode( $vol->authors );
$type=$vol->printType;
/* etc */
echo $title, $authors, $type, '<br />';//etc
}
/* to clearly see the data structure try this: */
echo '<pre>',print_r($obj,true),'</pre>';
Will output
Steve JobsWalter IsaacsonBOOK
stdClass Object
(
[kind] => books#volumes
[totalItems] => 1
[items] => Array
(
[0] => stdClass Object
(
[kind] => books#volume
[id] => 8U2oAAAAQBAJ
[etag] => Cfd5hfOLjks
[selfLink] => https://www.googleapis.com/books/v1/volumes/8U2oAAAAQBAJ
[volumeInfo] => stdClass Object
(
[title] => Steve Jobs
[authors] => Array
(
[0] => Walter Isaacson
)
[publisher] => Simon and Schuster
[publishedDate] => 2011
[description] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
[industryIdentifiers] => Array
(
[0] => stdClass Object
(
[type] => ISBN_13
[identifier] => 9781451648546
)
[1] => stdClass Object
(
[type] => ISBN_10
[identifier] => 1451648545
)
)
[readingModes] => stdClass Object
(
[text] =>
[image] =>
)
[pageCount] => 630
[printType] => BOOK
[categories] => Array
(
[0] => Biography & Autobiography
)
[averageRating] => 4
[ratingsCount] => 3904
[maturityRating] => NOT_MATURE
[allowAnonLogging] =>
[contentVersion] => 0.3.0.0.preview.0
[imageLinks] => stdClass Object
(
[smallThumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api
[thumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
)
[language] => en
[previewLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&printsec=frontcover&dq=isbn:9781451648546&hl=&cd=1&source=gbs_api
[infoLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&dq=isbn:9781451648546&hl=&source=gbs_api
[canonicalVolumeLink] => https://books.google.com/books/about/Steve_Jobs.html?hl=&id=8U2oAAAAQBAJ
)
[saleInfo] => stdClass Object
(
[country] => GB
[saleability] => NOT_FOR_SALE
[isEbook] =>
)
[accessInfo] => stdClass Object
(
[country] => GB
[viewability] => PARTIAL
[embeddable] => 1
[publicDomain] =>
[textToSpeechPermission] => ALLOWED_FOR_ACCESSIBILITY
[epub] => stdClass Object
(
[isAvailable] =>
)
[pdf] => stdClass Object
(
[isAvailable] =>
)
[webReaderLink] => http://play.google.com/books/reader?id=8U2oAAAAQBAJ&hl=&printsec=frontcover&source=gbs_api
[accessViewStatus] => SAMPLE
[quoteSharingAllowed] =>
)
[searchInfo] => stdClass Object
(
[textSnippet] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
)
)
)
)

Echo out from a multidimensional array

I have this array:
Array
(
[result] => Array
(
[lastModified] => 1465097340000
[name] => Ulminia
[realm] => Zangarmarsh
[battlegroup] => Rampage
[class] => 3
[race] => 4
[gender] => 1
[level] => 100
[achievementPoints] => 14915
[thumbnail] => hellscream/74/113337162-avatar.jpg
[calcClass] => Y
[faction] => 0
[items] => Array
(
[averageItemLevel] => 710
[averageItemLevelEquipped] => 709
[head] => Array
(
[id] => 125899
[name] => Warmongering Gladiator's Helm
[icon] => inv_helm_mail_raidhunter_p_01
[quality] => 4
[itemLevel] => 710
[tooltipParams] => Array
(
[transmogItem] => 71356
[timewalkerLevel] => 100
)
I want to echo out from the [head] array the [id] and the [quality]. If i just echo out the [id] everything works, but if i want to echo out the [quality] too, it doesn´t work.
My code:
$items = $r['result']['items'];
echo 'Head: '.$items['head']['id']['quality']."\n";
foreach($items['head']['tooltipParams'] as $key => $value){
echo 'head_'.$key.': '.$value.'\n';
}
echo $items['head']['id']['quality'];
The above statement means you are printing out the subkey "quality" of key "id", which doesn't exist.
You need to concatenate both key values as follows:
echo $items['head']['id'] . ' ' . $items['head']['quality'];
... or
echo $items['head']['id'], ' ', $items['head']['quality'];
$items['head']['id']['quality']."\n"; is trying to read the element with the key quality inside the array stored inside id. However, id is not an array, which is why this fails.
In order to read two fields, you need to read them seperately:
echo 'Head: ID=' . $items['head']['id'] . ', quality = ' . $items['head']['quality'] . "\n";
Notice that the id and the quality are in the same array.
//ID
echo $items['head']['id'];
//Quality
echo $items['head']['quality'];

Someone Help Me To Print This Array Using Css Or In Tables

Can someone please help me to print this data using tables or css or bootstrap..?
PHP Code Used:
$url = "http://some-website.com/api/message";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$json = json_decode($content, true);
$count=count($json);
print_r ($json);
Result:
Array
(
[success] => 1
[result] => Array
(
[0] => Array
(
[id] => 12491055
[device_id] => 18398
[message] => hi there!
[status] => received
[send_at] => 0
[queued_at] => 0
[sent_at] => 0
[delivered_at] => 0
[expires_at] => 0
[canceled_at] => 0
[failed_at] => 0
[received_at] => 1456228673
[error] => N/A
[created_at] => 1456271873
[contact] => Array
(
[id] => 3077686
[name] => charan
[number] => 123456789
)
)
)
)
I'm new in this php field so don't try to make your answers bit difficult one for me to understand or execute.
i want it to be printed like:
Name: some one
Message: Hi
Etc.........
just like online desposal mobile numbers & message's services sites
Thanks In Advance!
Just look at the array you already have, and drill down.
echo "Name: " . $json['result'][0]['contact']['name'];
Or:
echo "Message: " . $json['result'][0]['message'];
use foreach() to print your array.example:
$tab=array('name'=>'Jack','last name'=>'sparrow');
foreach($tab as $key=>$elem)
{
echo "$key : $elem <br>";
}
//the result
//name: jack
//last name : sparrow

Parsing JSON Results with PHP - Yahoo Search API

I am able to retrieve results from yahoo with my API key, using the instructions found on the yahoo developers website. http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#
Code:
if ($_POST['query'])
{
$newline="<br />";
$query = urlencode("'{$_POST['query']}'");
require("OAuth.php");
$cc_key = "key goes here";
$cc_secret = "secret goes here";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "$query";
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$rsp = curl_exec($ch);
$results = json_decode($rsp);
print_r($results);
}
Using print_r($results) as shown above, I get results, such as the following (extract of first three results shown from searching for "elephant"):
PLEASE NOTE I HAVE CHANGED THE URLS TO "WWW" AS I REQUIRE AT LEAST 10 REPUTATION TO POST MORE THAN 2 LINKS.
stdClass Object ( [bossresponse] => stdClass Object ( [responsecode]
=> 200 [web] => stdClass Object ( [start] => 0 [count] => 50 [totalresults] => 36800000 [results] => Array ( [0] => stdClass Object
( [date] => [clickurl] => WWW [url]
=> WWW [dispurl] => en.wikipedia.org/wiki/Elephant [title] => Elephant - Wikipedia, the
free encyclopedia [abstract] => Elephant trunks have multiple
functions, including breathing, olfaction, ... One elephant has been
observed to graze by kneeling on its front legs, ... ) [1] => stdClass
Object ( [date] => [clickurl] =>
WWW [url] =>
WWW [dispurl] =>
www.defenders.org/elephant/basic-facts [title] => Elephant | Basic
Facts About Elephants | Defenders of Wildlife [abstract] => Elephant.
Basic Facts About Elephants More on Elephant: Threats to Elephants »
More on Elephant: Basic Facts . Threats. What Defenders Is Doing to
Help. What You Can ... ) [2] => stdClass Object ( [date] => [clickurl]
=> WWW
[url] =>
WWW
[dispurl] => kids.nationalgeographic.com/.../african-elephant [title]
=> African Elephant Facts and Pictures -- National Geographic Kids [abstract] => Kids' feature about elephants, with photographs, video,
audio, fun facts, an e-mail postcard, and links to other animals. )
[3] => stdClass Object ( [date] => [clickurl] =>
WWW [url]
=> WWW [dispurl] => elephant.elehost.com/About_Elephants/about_elephants.htm
[title] => About Elephants [abstract] => All about elephants on the
Elephant Information Repository! This page includes a summary of
elephant related facts to get you inducted in to the world of
elephants. )
I have attempted to output the results, in a legible format, as follows:
Code Attempt 1:
foreach ($results->{ 'results' } as $item )
{
echo "<font color ='blue'>{$item->{ 'title' }}</font>".": "."$newline"."$newline".$item->{ 'abstract' }."\n\n";
}
I also tried the following, without success:
Code Attempt 2:
echo $results['results']['url'];
echo $results['results']['title'];
echo $results['results']['abstract'];
Any ideas on what to do?
Thanks.
I've noticed you just copy-pasted the code from the documentation's code examples, but never mind that.
You're accessing the results array the wrong way:
foreach ($results->bossresponse->web->results as $result)
{
//do stuff
echo $result->title.'<br/>';
}
Or, as cptnk suggested:
$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
//$result is array here, but do the same stuff
echo $result['title'].'<br/>';
}
Or, combine the two
foreach($results->bossresponse->web->results as $result)
{
$result = (array) $result;//casts stdClass to array
printf('%s<br/>', $result['url'], $result['title']);
}

Yahoo Boss API Pagination

I am getting this json output from yahoo boss api. It goes on for 50 results, but, I have pasted only the first two...
(
[bossresponse] => stdClass Object
(
[responsecode] => 200
[web] => stdClass Object
(
[start] => 0
[count] => 50
[totalresults] => 2750000
[results] => Array
(
[0] => stdClass Object
(
[date] =>
[clickurl] => http://www.apple.com/ipad/
[url] => http://www.apple.com/ipad/
[dispurl] => www.apple.com/<b>ipad</b>
[title] => Apple - <b>iPad</b>
[abstract] => <b>iPad</b> is a magical window where nothing comes between you and what you love. And it comes in two sizes.
)
[1] => stdClass Object
(
[date] =>
[clickurl] => http://en.wikipedia.org/wiki/IPad
[url] => http://en.wikipedia.org/wiki/IPad
[dispurl] => en.wikipedia.org/wiki/<b>IPad</b>
[title] => <b>iPad</b> - Wikipedia, the free encyclopedia
[abstract] => The <b>iPad</b> is a line of tablet computers designed and marketed by Apple Inc., which runs Apple's iOS operating system. The first <b>iPad</b> was released on April 3, 2010; the ...
)
[2] => stdClass Object
(
[date] =>
[clickurl] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[url] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[dispurl] => www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3A<b>ipad</b>
[title] => Amazon.com: <b>ipad</b>
[abstract] => Considering an <b>iPad</b>? Compare it to Kindle Fire HD Check out our easy side-by-side comparison chart to see how the newest <b>iPad</b> stacks up to Kindle Fire HD 8.9".
)
I use the following code in php to connect to the api and display the results...
**//connect to yahoo api and get results in json**
<?php
require("OAuth.php");
$cc_key = "**confidential**";
$cc_secret = "**confidential**";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "yahoo";
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp);
?>
**// Present results in html/php**
<div id="resultsdiv">
<?php
foreach($results->bossresponse->web->results as $result)
{
echo '<h3><a href='.$result->url.'>'.$result->title.'</br>'.$result->abstract.'</a></h3>';
}
?>
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Any help is appreciated.
Thanks.
According to the Yahoo! BOSS documentation, specifically the Universal Arguments section, it looks like you can use the start and count parameters to adjust the pagination of results. It looks like the default return count is 50 which matches what you observed.
In your code example you can adjust by adding:
$args["start"] = 0; // increment as needed
$args["count"] = 10;

Categories