Get Data From Multidimensional Array [closed] - php

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)

Related

Loop multidimensional array from mysql database using php

I can't for the life me return single values of my multidimensional array from database. For example, I want to return the value of each key to return in table columns.
This is the array coming from the database:
Array
(
[0] => stdClass Object
(
[student_id] => lvzr0001
[fname] => Hamza
[lname] => ibrahimi
[student_email] => Hamza_ib2#hotmail.com
[course] => CPAN 220 D30
[full_name] => asdfddd
[institution] => asdf
[position] => sadf
[proc_email] => Hamza_ib2#hotmail.com
[phone] => 14168334599
[address] => 20 edgecliffe golfway
[city] => Toronto
[prov_state] => Ont
[postal_code] => M3C 3A4
[country] => Canada
[comments] => adfadsfasdfasdfas
)
[1] => stdClass Object
(
[student_id] => 56gfdsgdfs
[fname] => zxcv
[lname] => cvcvz
[student_email] => dsfb2#hotmail.com
[course] => ELIC 101 90
[full_name] => dfa
[institution] => asdf
[position] => zxcvzxcv
[proc_email] => zxcvzxvc#hotmail.com
[phone] => 4002452345
[address] => 102 yorkland st
[city] => Richmond Hill
[prov_state] => Ont
[postal_code] => l4s1a1
[country] => Canada
[comments] => xzcvzxcv
)
)
I want to get a specific column result like this:
<?php
global $wpdb;
$displayQuery = $wpdb->get_results("SELECT * FROM viewoffcampusproctorrequests");
echo '<pre>';
print_r ($displayQuery);
echo '</pre>';
foreach($displayQuery as $key => $value){
foreach($value as $title => $description){
echo $description['fname'];
}
}
But I only get the entire key values when I echo $description;. How would I access each key item in my array?
You're close: $value is an object, so you can retrieve a particular key/value pair. If you want the value for fname for each object:
foreach($displayQuery as $key => $value){
echo $value->fname;
}

Getting out the value of a key in multidimentional array in php

In my php query I got this output:
{"projects":[{"id":127,"name":"efrat","status":{"id":10,"name":"development","label":"development"},"description":"","enabled":true,"view_state":{"id":10,"name":"public","label":"public"},"access_level":{"id":90,"name":"administrator","label":"administrator"},"custom_fields":[{"id":1,"name":"Customer email","type":"email","default_value":"","possible_values":"","valid_regexp":"","length_min":0,"length_max":50,"access_level_r":{"id":10,"name":"viewer","label":"viewer"},"access_level_rw":{"id":10,"name":"viewer","label":"viewer"},"display_report":true,"display_update":true,"display_resolved":true,"display_closed":true,"require_report":false,"require_update":false,"require_resolved":false,"require_closed":false}],"versions":[],"categories":[{"id":93,"name":"Monitor","project":{"id":0,"name":null}},{"id":31,"name":"Proactive","project":{"id":0,"name":null}},{"id":30,"name":"Project","project":{"id":0,"name":null}},{"id":29,"name":"Support","project":{"id":0,"name":null}}]}]}
after using 'json_decode' method on it, I get this:
"(
[projects] => Array
(
[0] => Array
(
[id] => 127
[name] => myprojectname
[status] => Array
(
[id] => 10
[name] => development
[label] => development
)
[description] =>
[enabled] => 1
[view_state] => Array
(
[id] => 10
[name] => public
[label] => public
)
[access_level] => Array
(
[id] => 90
[name] => administrator
[label] => administrator
)
[custom_fields] => Array
(
[0] => Array
(
[id] => 1
[name] => Customer email
[type] => email
[default_value] =>
[possible_values] =>
[valid_regexp] =>
[length_min] => 0
[length_max] => 50
[access_level_r] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[access_level_rw] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[display_report] => 1
[display_update] => 1
[display_resolved] => 1
[display_closed] => 1
[require_report] =>
[require_update] =>
[require_resolved] =>
[require_closed] =>
)
)
[versions] => Array
(
)
[categories] => Array
(
[0] => Array
(
[id] => 93
[name] => Monitor
[project] => Array
(
[id] => 0
[name] =>
)
)
[1] => Array
(
[id] => 31
[name] => Proactive
[project] => Array
(
[id] => 0
[name] =>
)
)
[2] => Array
(
[id] => 30
[name] => Project
[project] => Array
(
[id] => 0
[name] =>
)
)
[3] => Array
(
[id] => 29
[name] => Support
[project] => Array
(
[id] => 0
[name] =>
)
)
)
)
)
)"
In my PHP, how can I release the "name" object value (the result should be 'myprojectname') from this array? I've tried many foreach loops that got me nowhere.
Thank you,
It looks like you have one object, that when decoded actually only has one array item. So, in your case, ‘myprojectname’ may simply be “$projects[0][‘name’]”
If many array items, you could
foreach ($projects as $project) {
echo $project[‘name’];
}
EDIT: I took object provided and json_decoded it myself, it doesn't match the json_decoded item presented by OP -- the first image shows the code to var_dump 'name' OP desired, part of the code also below:
$decoded = json_decode($obj);
$projects = $decoded->projects;
$name = $projects[0]->name;
Your 'projects' contains an array ("projects":[{"id":127, ... }]). I assume that the 'projects'-array might contain multiple 'project'-objects like this?
{
"projects":
[
{
"id":127,
"name":"my-project"
},
{
"id":128,
"name":"my-other-project"
}
]
}
In that case you need the arrow notation to access the name property, for example:
foreach ($projects as $project_object) {
foreach ($project_object as $project) {
echo $project->name . '<br/>';
}
}
EDIT:
I took a minimal code example of the OP and got the expected result:
Can you add more details in your code snippets in your original question or provide us with a working example of your code?
There are some online PHP sandboxes that can help you with this. For example: I stripped out all code that does not seem related to your question and got the result you are looking for in two different ways:
http://sandbox.onlinephpfunctions.com/code/009c53671fd9545e4fcecfe4b0328974381ee2ce
It is also a good idea to sum up all the foreach loops that you already tried, so we can see if you were nearly there with your own solution. This way we can understand your question better and it prevents us from offering solutions that you already used.

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;
}

Iterating through array in PHP for Yahoo API

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>";

how to get individual values from this array

I got this result when I printed the array print_r($post);
Array ( [0] => Array ( [0] => stdClass Object ( [subscriber_id] => 80010055 [cto_id] => [name] => n [mobile] => 1234564444 [state] => [city] => fsd [cto_subscriber_id] => 0 [password] => e10adc3949ba59abbe56e057f20f883e [email] => n#n.com [email_verified] => 1 [ip_address] => ::1 [last_login_time] => 2012-10-24 11:37:19 ) ) [1] => Array ( [0] => stdClass Object ( [subscriber_id] => 80010055 [ip_address] => [landline_number] => [sex] => 0 [dob] => 0000-00-00 00:00:00 [marital_status] => hfg [state] => [addres] => fgh [city] => fghfg [pincode] => fghfgh ) ) )
How can I get single values
Typecast it to array?
$arr = (array)$post[0][0];
And then you'll be able to loop through it as through normal array
foreach ($arr as $key => $value){....}
foreach $post as $sub {
foreach $sub as $single {
echo $single;
}
}
Think you should learn the basics of arrays and objects first.
Anyway in order to get the value of lets say subscriber_id you should use the following:
$post[0][0]->subscriber_id
First you get into the array and then get the value out of the Object

Categories