Iterating through array in PHP for Yahoo API - php

I am trying to return all of the answers to each question from the Yahoo API and right now my code is...
$appid= "myid";
$params = array(
'query' => $keyword, //enter your keyword here. this will be searched on yahoo answer
'results' => $maxLimit, //number of questions it should return
'type' => 'resolved', //only resolved questiosn will be returned. other values can be all, open, undecided
'output' => 'php', //result will be PHP array. Other values can be xml, json, rss
);
$yn = new yahooAnswer($appid);
//search questions
try
{
$questions = $yn->search_questions($params);
} catch (Exception $e)
{
echo ($e->getMessage());
}
foreach ($questions as $question)
{
//now get the answers for the question_id;
try
{
$answers = $yn->get_question(array('question_id'=>$question['id']));
//print out what you would like...All fields are location on this site http://developer.yahoo.com/answers/V1/getQuestion.html
print_r($answers);
//print_r( $answers['NumAnswer']);
//print_r( $answers['Content'] . "<br/>");
//print_r($answers['chosenanswer'] . "<br/>");
//echo $answers['UserNick']. "<br />";
echo "<hr>";
} catch (Exception $e)
{
echo($e->getMessage());
}
}
and I get this as the return when I print_r($answers)...
Array
(
[id] => 20090408072929AAbYFdK
[type] => Answered
[Subject] => Do you like apples???????????
[Content] => Just wanted to know how many people really like apples out there.
[Date] => 2009-04-08 07:29:29
[Timestamp] => 1239175769
[Link] => http://answers.yahoo.com/question/?qid=20090408072929AAbYFdK
[Category] => Array
(
[id] => 396545372
[content] => Other - Food & Drink
)
[UserId] => l3ja8nMSaa
[UserNick] => Bob
[UserPhotoURL] => http://l.yimg.com/sc/28232/answers1/images/a/i/identity/nopic_48.png
[NumAnswers] => 10
[NumComments] => 0
[ChosenAnswer] => apples are delish
i luv the dark red apples
the green ones
apple sauce
apple pie (with vanilla ice cream)
[ChosenAnswererId] => ihAFSbClaa
[ChosenAnswererNick] => SantaFe95
[ChosenAnswerTimestamp] => 1239176570
[ChosenAnswerAwardTimestamp] => 1240818783
[Answers] => Array
(
[0] => Array
(
[Content] => Apples are my second favourite fruit.
[Reference] =>
[Best] =>
[UserId] => rZMc7vTXaa
[UserNick] => gemstone
[Date] => 2009-04-08 07:36:21
[Timestamp] => 1239176181
)
[1] => Array
(
[Content] => when i was little i used to love them because they were very hard to find where we lived and hardly ever got to eat any.
then when i grew up and had to go on a diet where i had to eat 5 or 6 a day i learned to hate them.
[Reference] =>
[Best] =>
[UserId] => aecb87753b7a91041ba0f8e18327da41aa
[UserNick] => Missy ~
[Date] => 2009-04-08 07:36:38
[Timestamp] => 1239176198
)
[2] => Array
(
[Content] => Yep - granny smith, braeburn, and honeycrisp are my favorites
[Reference] =>
[Best] =>
[UserId] => 9LYQ34Bvaa
[UserNick] => sportslover7
[Date] => 2009-04-08 07:36:45
[Timestamp] => 1239176205
)
[3] => Array
(
[Content] => apples are awesome. But, I can't eat them cold, my teeth are WAY TOO sensitive.
[Reference] =>
[Best] =>
[UserId] => l63HXU7kaa
[UserNick] => Kira
[Date] => 2009-04-08 07:39:33
[Timestamp] => 1239176373
)
[4] => Array
(
[Content] => GALA APPLES
[Reference] =>
[Best] =>
[UserId] => tsad330Maa
[UserNick] => Lie T
[Date] => 2009-04-08 07:40:58
[Timestamp] => 1239176458
)
[5] => Array
(
[Content] => Of course. But I only get organic apples. Regular apples are on the "dirty dozen" list for being sprayed with loads pesticides and chemicals...yuck!
[Reference] =>
[Best] =>
[UserId] => 1939a4787cfedfac7deb18c16c99dde2aa
[UserNick] => Jami J
[Date] => 2009-04-08 07:42:03
[Timestamp] => 1239176523
)
[6] => Array
(
[Content] => apples are delish
i luv the dark red apples
the green ones
apple sauce
apple pie (with vanilla ice cream)
[Reference] =>
[Best] => 5
[UserId] => ihAFSbClaa
[UserNick] => SantaFe95
[Date] => 2009-04-08 07:42:50
[Timestamp] => 1239176570
)
[7] => Array
(
[Content] => OMG I love Granny Smith Apples (You know, the green ones)
[Reference] =>
[Best] =>
[UserId] => yIiKFxU5aa
[UserNick] => That half-black half-white girl
[Date] => 2009-04-08 07:50:20
[Timestamp] => 1239177020
)
[8] => Array
(
[Content] => yeah
[Reference] =>
[Best] =>
[UserId] => AA11402528
[UserNick] => Wambo
[Date] => 2009-04-08 07:58:26
[Timestamp] => 1239177506
)
[9] => Array
(
[Content] => i love apples ! An apple a day keeps the doctor away the trick it to hit him on the head with it
[Reference] =>
[Best] =>
[UserId] => ElxlHvL5aa
[UserNick] => blindartist47
[Date] => 2009-04-08 08:15:05
[Timestamp] => 1239178505
)
)
)
But when I use print_r(answers['Content']) I only get one of them printed, not all of them.
Any ideas on how to go about this issue? There should be six answers being printed

Thats because the array contains a new Array of answers called ['Answers']. So if you want to print each answer you get, you will have to do the following:
try
{
$answers = $yn->get_question(array('question_id'=>$question['id']));
//print out what you would like...All fields are location on this site http://developer.yahoo.com/answers/V1/getQuestion.html
foreach($answers['Answers'] as $answer)
{
print_r($answer['Content']);
echo "<hr>";
}
}
catch (Exception $e)
{
echo($e->getMessage());
}
E: When you dump an array with print_r() or var_dump(), alsways wrap up the result in pretags so you can easily see what's nested inside an new array etc.
echo "<pre>";
print_r($answers);
echo "</pre>";

Related

Echo arrays in foreach loop codeigniter

I've been using codeigniter for years but there's a really big gap in between so i always find myself in situations where i forgot how to do things and its almost midnight here so my brain isn't working fast. Can someone show me how to echo the array i have and explain to me how they are processed in the foreach loops?
I have this code in my model to take the rows in 2 tables.
public function tag_genre(){
$result['tag'] = $this->db->get('tags')->result_array();
$result['genre'] = $this->db->get('genre')->result_array();
return $result;
}
And I have this in my controller
public function view_publish_story(){
$data = array('tag_genre' => $this->story_model->tag_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
I used print_r in my view and this is the result. Seeing this just confuses me more. It's been atleast 2 years since i even dealt with foreach loops.
Array ( [tag] => Array ( [0] => Array ( [tag_id] => 1 [tag_name] =>
LitRPG ) [1] => Array ( [tag_id] => 2 [tag_name] => Virtual Reality )
[2] => Array ( [tag_id] => 3 [tag_name] => Cyberpunk ) [3] => Array (
[tag_id] => 4 [tag_name] => Reincarnation ) [4] => Array ( [tag_id] =>
5 [tag_name] => Summoned Hero ) [5] => Array ( [tag_id] => 6
[tag_name] => Martial Arts ) [6] => Array ( [tag_id] => 7 [tag_name]
=> Slice of Life ) [7] => Array ( [tag_id] => 8 [tag_name] => Overpowered ) [8] => Array ( [tag_id] => 9 [tag_name] => Non-Human )
[9] => Array ( [tag_id] => 10 [tag_name] => Anti-hero ) ) [genre] =>
Array ( [0] => Array ( [genre_id] => 1 [genre_name] => action ) [1] =>
Array ( [genre_id] => 2 [genre_name] => adventure ) [2] => Array (
[genre_id] => 3 [genre_name] => comedy ) [3] => Array ( [genre_id] =>
4 [genre_name] => Drama ) [4] => Array ( [genre_id] => 5 [genre_name]
=> Fantasy ) [5] => Array ( [genre_id] => 6 [genre_name] => Historical ) [6] => Array ( [genre_id] => 7 [genre_name] => Horror ) [7] => Array
( [genre_id] => 8 [genre_name] => Psychological ) [8] => Array (
[genre_id] => 9 [genre_name] => Romance ) [9] => Array ( [genre_id] =>
10 [genre_name] => Sci-fi ) [10] => Array ( [genre_id] => 11
[genre_name] => Mystery ) [11] => Array ( [genre_id] => 12
[genre_name] => Tragedy ) [12] => Array ( [genre_id] => 13
[genre_name] => Short Story ) [13] => Array ( [genre_id] => 14
[genre_name] => Satire ) ) )
I've been looking at various questions regarding arrays from assoc to multidimensional and other stuff. Then i finally visited php manual for foreach loop and i finally was able to echo the array. The problem now is that although it echoes my array it also has an error for each, i can probably fix the error part by declaring it as a defined variable. My question is, is there any other better way? or any improvement on how i made my array to make it cleaner or easier to print?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo $values['tag_name'];
}
}
UPDATE: i changed the way i made the array.
This is now my model:
public function get_tags(){
$query = $this->db->get('tags')->result_array();
foreach($query as $row){
$result[$row['tag_id']] = $row['tag_name'];}
return $result;
}
public function get_genre(){
$query = $this->db->get('genre')->result_array();
foreach($query as $row){
$result[$row['genre_id']] = $row['genre_name'];}
return $result;
}
and my controller:
public function view_publish_story(){
$data = array('tag' => $this->story_model->get_tags(), 'genre' => $this->story_model->get_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
and in my view:
<tr>
<div class="form-group">
<td><label for="genre">Genre</label></td>
<?php
foreach($genre as $genre_id => $genre_name){
echo "<td><label class='checkbox-inline'><input type='checkbox' value=''>".$genre_name."</label><td>";
}
?>
</div>
</tr>
My problem now is that, how do i fit all these into my table? I just ruined my table right now since i echoed them all in a single line. How do i do it so that it is printed in 3 columns?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo '<pre>';
echo $values['tag_name'];
}
}
this will format your array in a way you can read it and understand it.

Extract data from Array/Object in PHP?

First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}

Get Data From Multidimensional Array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have an php array
Array
(
[results] => Array
(
[0] => Array
(
[birthday] => 11-Apr-2014
[category] => Array
(
[0] => 204
[1] => 300
[2] => 304
)
[city] => Dhaka
[country] => Bangladesh
[email] => javaorjava#gmail.com
[fullName] => biplob
[gender] => Male
[inspirational] => Run to dream
[phone] => aapbd1
[photo] => Array
(
[__type] => File
[name] => 8bef9bc3-ee64-45df-9698-0466e255c1bd-profilePhoto.jpg
[url] => http://files.com/c2dcf728-e2a3-4b2d-a8c8-6ec9b3c6502a/8bef9bc3-ee64-45df-9698-0466e255c1bd-profilePhoto.jpg
)
[username] => aapbd
[website] => http://ss.com
[createdAt] => 2014-04-10T19:01:16.396Z
[updatedAt] => 2014-04-28T07:36:18.459Z
[objectId] => IQSCdXE2hI
)
[1] => Array
(
[birthday] => 09-Apr-1982
[category] => Array
(
[0] => 204
[1] => 307
[2] => 311
[3] => 313
[4] => 102
[5] => 103
[6] => 105
[7] => 107
)
[city] => Madrid
[country] => Spain
[coverPhoto] => Array
(
[__type] => File
[name] => aa53cf65-47af-464d-aa49-88202f91388f-coverPhoto.jpg
[url] => http://files.com/c2dcf728-e2a3-4b2d-a8c8-6ec9b3c6502a/aa53cf65-47af-464d-aa49-88202f91388f-coverPhoto.jpg
)
[description] => a lazy man
[email] => skio#yahoo.com
[fullName] => Sjun
[gender] => Male
[inspirational] => Honesty is the best policy
[phone] => 135469
[photo] => Array
(
[__type] => File
[name] => a1aec283-f3c7-484c-a8b2-a0b09c5f3023-profilePhoto.jpg
[url] => http://files.com/c2dcf728-e2a3-4b2d-a8c8-6ec9b3c6502a/a1aec283-f3c7-484c-a8b2-a0b09c5f3023-profilePhoto.jpg
)
[username] => asa
[website] =>
[createdAt] => 2014-04-09T07:58:19.043Z
[updatedAt] => 2014-05-07T11:13:40.671Z
[objectId] => iVb6olefaT
)
)
)
I'm trying to practice/learn foreach loops in PHP. I understand basic foreach. But I struggle with multi-dimensionals.
I want to get my every array birthday,photo name,photo url,category.
But I cant retrieve those correctly with foreach loop
Use a simple foreach() for iterating over MD arrays..
foreach($yourarray['results'] as $k=>$arr)
{
echo $arr['birthday'];
echo $arr['photo']['name'];
echo $arr['photo']['url'];
}
Let's say your array is $data,
foreach ($data['results'] as $key => $value)
echo $value['birthday'];
echo $value['photo']['name'];
echo $value['photo']['url'];
}
use $key as index value.
This is how you can access your nested array, regardless the amount of categories:
// Loop over all elements of main array element
foreach($array['results'] as $arr_key => $arr_value) {
// Loop over children
foreach($arr_value as $key => $value) {
// Element is array (like 'category' or 'photo')
if(is_array($value)) {
foreach($value as $sub_key => $sub_value) {
echo $key."[".$sub_key."] = ".$sub_value;
}
// Element is no array
} else {
echo $key." = ".$value;
}
}
}
(Example)

decode json response to get json parameter value

Here is my json response:
stdClass Object ( [is_claimed] => [rating] => 4 [mobile_url] => http://m.yelp.com/biz/the-waterboy-sacramento [rating_img_url] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/c2f3dd9799a5/ico/stars/v1/stars_4.png [review_count] => 455 [name] => The Waterboy [snippet_image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [rating_img_url_small] => http://s3-media4.ak.yelpcdn.com/assets/2/www/img/f62a5be2f902/ico/stars/v1/stars_small_4.png [url] => http://www.yelp.com/biz/the-waterboy-sacramento [menu_date_updated] => 1387494198 [reviews] => Array ( [0] => stdClass Object ( [rating] => 5 [excerpt] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [time_created] => 1395158338 [rating_image_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/f1def11e4e79/ico/stars/v1/stars_5.png [rating_image_small_url] => http://s3-media1.ak.yelpcdn.com/assets/2/www/img/c7623205d5cd/ico/stars/v1/stars_small_5.png [user] => stdClass Object ( [image_url] => http://s3-media1.ak.yelpcdn.com/photo/SZyFYvQmHWSLhK96SSzwwA/ms.jpg [id] => H0qUqWctz5Ms6qdeaIvjFw [name] => Lori T. ) [rating_image_large_url] => http://s3-media3.ak.yelpcdn.com/assets/2/www/img/22affc4e6c38/ico/stars/v1/stars_large_5.png [id] => bZznirkpADmW3Qcpc5u_VA ) ) [phone] => 9164989891 [snippet_text] => AMAZING again, went here last Thursday at 5:00pm. Greeted by friendly man, he asked if we had a reservation, I said, 'no, do we need one?' He said, I'm... [image_url] => http://s3-media1.ak.yelpcdn.com/bphoto/9e5sodvvP3p6_53wOqVTcg/ms.jpg [categories] => Array ( [0] => Array ( [0] => French [1] => french ) [1] => Array ( [0] => Italian [1] => italian ) ) [display_phone] => +1-916-498-9891 [rating_img_url_large] => http://s3-media2.ak.yelpcdn.com/assets/2/www/img/ccf2b76faa2c/ico/stars/v1/stars_large_4.png [menu_provider] => single_platform [id] => the-waterboy-sacramento [is_closed] => [location] => stdClass Object ( [city] => Sacramento [display_address] => Array ( [0] => 2000 Capitol Ave [1] => Midtown [2] => Sacramento, CA 95811 ) [neighborhoods] => Array ( [0] => Midtown ) [postal_code] => 95811 [country_code] => US [address] => Array ( [0] => 2000 Capitol Ave ) [state_code] => CA ) )
which I get using:
$response = json_decode($data);
print_r($response);
echo $response["rating"]; //Why this does not give json response value?
Pass true into the second parameter of json_decode to return an array (which is how you're trying to access it):
$response = json_decode($data, true); // associative array returned
print_r($response);
echo $response["rating"]; // 4
Manual
Otherwise, access the rating as a property of the object that you've got:
$response = json_decode($data);
echo $response->rating; // 4

Get value in mutli array

How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}

Categories