Issue accessing elements of nested associative array - php

So I have some data that's coming back from a database query, and the resulting array (gotten with print_r) looks like this (it's assigned to a var called $locationData):
Array
(
[0] => Array
(
[id] => 1
[location_name] => Cook Minnesota
[location_lat] => 47.72037
[location_long] => -90.32667
)
[1] => Array
(
[id] => 2
[location_name] => Lake Minnesota
[location_lat] => 47.18238
[location_long] => -91.35301
)
[2] => Array
(
[id] => 3
[location_name] => St. Louis Minnesota
[location_lat] => 46.83572
[location_long] => -91.96299
)
)
I have a foreach loop that needs to grab the location_name from each. It looks like this:
foreach ($locationData as $location => $value ) {
echo '<p>name ' . $location['location_name']. '</p>';
}
I'm 99% certain this should work; it's basically the same code I've used a dozen times before. But the echo is not returning anything - not even the static text (<p>name). It's not throwing any errors, and if I try to do a print_r($location), I get nothing.
Any ideas? I'm sure it's something really simple.

You want $value['location_name'] because $value represents the arrays while $location represents the indexes of the arrays:
echo '<p>name ' . $value['location_name']. '</p>';

It is:
foreach ($locationData as $location => $value ) {
echo '<p>name ' . $value['location_name']. '</p>';
}

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.
)
)
)
)

Explode foreach to new array

I have JSON API response which look something like this
Array
(
[sections] => Array
(
[0] => Array
(
[id] => 115000089967
[url] => xxxxx
[html_url] => ArticleHTML1
[category_id] => 204458828
[position] => 0
[sorting] => manual
[created_at] => 2016-12-19T14:56:23Z
[updated_at] => 2017-02-03T08:23:04Z
[name] => ArticleName1
[description] =>
[outdated] =>
)
[1] => Array
(
[id] => 207077828
[url] => xxxxxx
[html_url] => ArticleHTML2
[category_id] => 204458828
[position] => 1
[sorting] => manual
[created_at] => 2016-11-14T09:28:30Z
[updated_at] => 2017-02-02T09:15:42Z
[name] => ArticleName2
[description] =>
[outdated] =>
)
)
[page] => 1
[per_page] => 30
[page_count] => 1
[sort_by] => position
[sort_order] => asc
)
I have successfully iterated this with foreach, so return looks like this:
ArticleName1 ArticleHTML1
ArticleName2 ArticleHTML2
So I took [name] and [html_url] from each like this:
$details1 = array('name');
$details2 = array('html_url');
foreach($sections['sections'] as $article) {
foreach($details1 as $detail) {
echo "$article[$detail] ";
}
foreach($details2 as $detail) {
echo "$article[$detail]\n";
}
}
But what I want next is that, that response should be exploded to one single array like this:
Array
(
[0] => ArticleName1 ArticleHTML1
[1] => ArticleName2 ArticleHTML2
)
I already managed to explode those to individual arrays:
foreach($sections['sections'] as $article) {
foreach($details1 as $detail) {
$name = "$article[$detail] ";
}
foreach($details2 as $detail) {
$url = "$article[$detail]\n";
}
$string = $name . $url;
$array = explode(' ', $string, 1);
print_r($array);
}
but I need just one array.
How? I'm lost or just doesn't understand, am I even close?
EDIT
The thing here is that the JSON dump is pretty large and I only need few things (name and url). So I was thinking that I first grab the whole thing, then I just take the names and urls (like the first foreach is doing), and then put those back to array. Because from those names and urls I need only last 12 keys, and taking those from sinlge array would be easy.
Tho it would be perfect, if I could sort out the keys which I don't want, in the first place. That would solve my problem. Then I wouldn't need a new array etc.
You're making this much more difficult than it needs to be. It's just a single loop:
$array = array();
foreach ($sections['sections'] as $article) {
$array[] = $article['name'] . ' ' . $article['html_url'];
}

PHP Nested foreach with Key

I have been trying to work this out for two days now and am hitting a brick wall. I have a skyscanner array that has flight itineraries where I have the flight
Leg - being Itineraries -> OutboundLegId -
and also the legs which shows the flight number - being
Legs -> FlightNumbers -> FlightNumber.
What I am trying to achieve is to display the Itinerary and then join the Flight Number on to that. But no matter what I try I cannot get this to work. I have read all about Keys on here and tried loads of examples but am coming up with nothing. Can someone point me in the right direction please?
Example arrays below
[Itineraries] => Array
(
[0] => Array
(
[OutboundLegId] => 13542-1610140610-29-0-13445-1610141240
[InboundLegId] => 13445-1610211340-29-0-13542-1610211640
[PricingOptions] => Array
(
[0] => Array
(
[Agents] => Array
(
[0] => 2174187
)
[QuoteAgeInMinutes] => 31
[Price] => 200.98
[DeeplinkUrl] => http://partners.api.skyscanner.net/apiservices/deeplink/v2?_cje=5JlLCgyPUKY0hT8T0Ybh6dL0Xf0htAiHTFX7RU79eeI3XvrsxvEqP1QUJAoHiHRd&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fUK%2fen-gb%2fGBP%2fcook%2f2%2f13542.13445.2016-10-14%2c13445.13542.2016-10-21%2fair%2fairli%2fflights%3fitinerary%3dflight%7c-32294%7c1152%7c13542%7c2016-10-14T06%3a10%7c13445%7c2016-10-14T12%3a40%2cflight%7c-32294%7c1153%7c13445%7c2016-10-21T13%3a40%7c13542%7c2016-10-21T16%3a40%26carriers%3d-32294%26passengers%3d1%2c0%2c0%26channel%3ddataapi%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d200.98%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3dskyscanner_b2b%26request_id%3d3bc96bda-fd7c-403a-b841-2ccc3c26071d%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-09-29T08%3a18%3a27
)
[Legs] => Array
(
[0] => Array
(
[Id] => 13542-1610140610-29-0-13445-1610141240
[SegmentIds] => Array
(
[0] => 1
)
[OriginStation] => 13542
[DestinationStation] => 13445
[Departure] => 2016-10-14T06:10:00
[Arrival] => 2016-10-14T12:40:00
[Duration] => 270
[JourneyMode] => Flight
[Stops] => Array
(
)
[Carriers] => Array
(
[0] => 105
)
[OperatingCarriers] => Array
(
[0] => 105
)
[Directionality] => Outbound
[FlightNumbers] => Array
(
[0] => Array
(
[FlightNumber] => 1152
[CarrierId] => 105
)
)
)
Assuming this is one big array and its called $data you can nest a couple of foreach loops.
I use foreach loops as I assume there are cases where this data structure get more complex than the one you show
foreach ( $data['Itineraries'] as $itin ) {
foreach ( $data['Legs'] as $legs) {
if ($legs['Id'] == $itin['OutboundLegId']) {
// we matched the itinerary with a leg
echo $legs['OutboundLegId'] . ' ' . $legs['FlightNumbers'][0]['FlightNumber'];
}
}
}
Use it as draft. Can't perform function without feedback.
Put proper arrays instead of {YOUR-ARRAY-WITH-LEGS} and {YOUR-ARRAY-WITH-ITINERARIES}
$sortedLegs = array_column('Id', {YOUR-ARRAY-WITH-LEGS});
$joinedArray = array_map(function($itinerary) use($sortedLegs){
if(array_key_exists($itinerary['OutboundLegId'],$sortedLegs)) {
$itinerary['legs'] = $sortedLegs[$itinerary['OutboundLegId']];
}
return $itinerary;
},{YOUR-ARRAY-WITH-ITINERARIES});

PHP Multidimensional Array of Objects

Can anyone help me with this little problem please? I need to get (echo) the name, id and link from an array but after hours trying I have not been able, see the array below... Thank you in advanced.
Array
(
[campaigns] => Array
(
[0] => Campaign Object
(
[name] => My name 1
[id] => 123456789012
[link] => 123456789012
)
[1] => Campaign Object
(
[name] => My name 2
[id] => 123456789012
[link] => 123456789012
)
[2] => Campaign Object
(
[name] => My name 3
[id] => 123456789012
[link] => 123456789012
)
)
)
If you know which campaign you want, you can get it like this:
echo($data['campaigns'][0]->name);
echo($data['campaigns'][0]->id);
echo($data['campaigns'][0]->link);
If you want to loop through all of them, you could do something like this:
foreach ($data['campaigns'] as $item) {
echo($item->name . "\n");
echo($item->id . "\n");
echo($item->link . "\n");
}
This is all a bit of a guess because we don't know what the Campaign class actually looks like - there may be a getName() method that you should be using instead of just accessing the name value directly, for example.
foreach ($array['campaigns'] as $key => $value){
echo "Name: ".$value->name." ID: ".$value->id." Link: ".$value->link."\n";
}
Question is a little light on details to debug but have you tried this?
<?php echo $campaigns[0]->name; ?>

Ordering Array by value

I'm pulling in a list of my vimeo albums using the Vimeo API and the looping three times through the array to get to the albums. It works fine.
My question is, I'm isolating the date, so how can I create a new array and sort it by the date?
While where at it, is there a way to jump to the third level of a multi-dimensional array?
$albums=$vimeo->call('vimeo.albums.getAll', array('user_id' => $myUserId));
$albums_array=object_2_array($albums);
foreach($albums_array as $album_array_two){
foreach($album_array_two as $album_array_three){
foreach($album_array_threeas $album){
if(stristr($album['title'],'conference')){
$title=$album['title'];
$description=$album['description'];
$date=stristr($album['description'],'.',true);
$year_comma=stristr($date,',');
$year=ereg_replace("[^0-9]", "", $year_comma);
$url_title='http://www.psfk.com/events/'.str_replace( " ", "-", strtolower($title));
$url=''.$title.'';
$thumb=$album['thumbnail_video']['thumbnails']['thumbnail'][1]['_content'];
echo '<li class="album">';
echo '<img src="'.$thumb.'" alt="'.$title.'" />';
echo '<div class="info">';
echo '<h2>'.$url.'</h2>';
echo $description.'<br />';
echo 'View...';
echo '</div></li>';
}
}
}
}
Sample of the array returning one item:
Array (
[generated_in] => 0.0828
[stat] => ok
[albums] => Array (
[on_this_page] => 7
[page] => 1
[perpage] => 50
[total] => 7
[album] => Array (
[0] => Array (
[id] => 1690236
[title] => Interviews
[description] =>
[created_on] => 2011-09-10 21:43:49
[total_videos] => 1
[url] => Array (
[0] => http://vimeo.com/album/1690236
)
[video_sort_method] =>
[thumbnail_video] => Array (
[id] => 28825158
[owner] => 718882
[title] => Where Inspiration Comes From [thumbnails] => Array (
[thumbnail] => Array (
[0] => Array (
[height] => 75
[width] => 100
[_content] => http://b.vimeocdn.com/ts/192/593/192593029_100.jpg
)
)
)
)
)
)
)
)
In order to sort by date, you can use the php_function array_multisort(). There is a good example on that page that I think shows what you need. I'll try to provide a better example using your data. Suppose after looping through your albums you end up with an array $myAlbums that looks like this:
Array (
[0] => Array(
[title] => My Title
[description] => some description
[date] 01-05-2011
)
[1] => Array(
.......
)
In order to sort this by date, you could do the following (taken from the example on the php page)
<?php
// Obtain a list of columns
foreach ($myAlbums as $key => $row) {
$date[$key] = $row['date'];
}
// Sort the data with volume descending, edition ascending
// Add $myAlbums as the last parameter, to sort by the common key
array_multisort($date, SORT_DESC, $myAlbums);
?>
Then you can print_r($myAlbums); and you should see that it is sorted. You might have to change the SORT_DESC flag depending on what formate your dates are in. I can't really explain HOW this works, because I'm still trying to figure it out myself... but I think it is what you need.

Categories