I am currently working with the following array,
Array
(
[0] => Array
(
[0] => Array
(
[candidate_id] => 41
[show_on_site] => urban talent
[first_name] => Barney
[surname] => Harwood
[gender] => male
[talent] => presenter
[skill] =>
[DOB] => 1983-11-30
[Location] => London
[contact_telephone] => 01234 567890
[contact_email] => barney#bluepeter.co.uk
[height] => 5' 1"
[eyes] => Brown
[hair_colour] => brown
[hair_length] => medium
[accents] => Native Northern, others include - Yorkshire, Liverpool, Manchester, Birmingham, Cockney, RP, Welsh, Scottish, German, American
[training] => n/a
[unions] => Member of the British Academy of Composers & Songwriters
Equity & MU Member
[visible] => yes
[availability] => yes
[availability_number] => 9999
[availability_order] => 0
[availability_comments] => BARNEY IS THE LATEST BLUE PETER PRESENTER AND CAN BE SEEN ON AIR MONDAYS & TUESDAYS AT 4.30PM ON BBC
[spotlight_url] =>
[youtube_showreel] =>
[date_created] => 2011-11-02 10:44:37
[created_by] => 1
)
)
[1] => Array
(
[0] => Array
(
[candidate_id] => 42
[show_on_site] => urban talent
[first_name] => Simon
[surname] => Ainley
[gender] => male
[talent] => actor
[skill] =>
[DOB] => 1987-06-12
[Location] => Huddersfield
[contact_telephone] => 01484 532751
[contact_email] => simonainley#the-factory.co.uk
[height] => 5' 1"
[eyes] => blue
[hair_colour] => brown
[hair_length] => short
[accents] => Accents
[training] => Training
[unions] => Union Membership
[visible] => yes
[availability] => yes
[availability_number] => 9999
[availability_order] => 0
[availability_comments] => Availability Comments
[spotlight_url] => http://www.google.com
[youtube_showreel] => http://www.youtube.com/watch?v=sP4NMoJcFd4
[date_created] => 2011-11-08 11:28:12
[created_by] => 1
)
)
)
as you can see it is an array within an array type situation, I am trying to loop through it to pull out the first_name + surname of each entry, however I get the following error when I try to do it,
A PHP Error was encountered
Severity: Notice
Message: Undefined index: firstname
Filename: admin/candidate_list.php
Line Number: 5
I looping through it like this at the moment,
<?php foreach ($candidates as $k => $v) : ?>
<li><?php echo $v[0]['first_name']. " ".$v[0]['surname']; ?></li>
What am i doing wrong?
What does this give you?
<?php foreach ($candidates as $k => $v) print_r($v); ?>
I don't know how $v['id'] would be defined either given that array, so there's something else you're leaving out...
And you're using site_url()... Do I smell CodeIgniter? ;)
Your array is too deep for that loop. I am assuming that $candidates is the name of the whole big array? You don't need each candidate in their own array, try getting your results in an array that has one less level and that foreach will work.
<?
for($i=0; $i=50; $i++){
foreach ($candidates[$i] as $v){
?>
<li><?php echo $v[0]['first_name']. " ".$v[0]['surname']; ?></li>
<?
}
}
?>
Related
I am looping through an array, and I want to print some of the keys and values of the array.
I can print the first array that is index 0 but I can not print sub array.
#foreach($data[0] as $k => $v)
{{$v['bill_no']}} //prints b-0002
#foreach($v['customer_details'] as $kk => $vv)
Customer Name : {{$vv['name']}} //gives the error
#endforeach
#endforeach
This is my array:
Array ( [0] =>
Array ( [0] =>
Array ( [id] => 14 [customer_id] => 2 [referral_id] => 1 [sq_id] =>
[bill_no] => b0002 [bill_date] => 07-09/2018 [payment_mode] => cash
[delivered_by] => tsr [net_total] => 15000
[customer_details] => Array ( [id] => 2 [code] =>
csdc [name] => jhon k [address] => mangalore [telephone] => cs [mobile]
=> sd [tin] => sdc [gstin] => dsc
[opening_balance] => 10000 [remarks] => sd [credit_limit] => 100
[bank_name] => HDFC [account_no] =>
0022 [ifsc] => 5588 [account_name] => jhon [created_at] => 2018-08-13
22:04:10 [updated_at] => 2018-12-24
09:39:00 ) [sold_items] =>
I want to print the name of the customer
Name: {{$vv['name']}}
Try this out:
#foreach($data[0] as $k => $v)
{{$v['bill_no']}} //prints b-0002
#foreach($v['customer_details'] as $vv) // As it is associative array, we are not going to use `$kk`
Customer Name : {{$vv['name']}} //Now this should work.
#endforeach
#endforeach
I have a notifications section on my site and I am getting data from my table. There can be child notifications assigned to their parent, so I have parent_id in the table as shown below:
Below is the array I am getting
Array
(
[0] => stdClass Object
(
[user_title] => Mr
[user_firstname] => Richard
[user_lastname] => Knight-Gregson
[assignee_title] => Mr
[assignee_firstname] => Richard
[assignee_lastname] => Knight-Gregson
[created] => 2015-03-26 11:40:20
[id] => 61
[user_id] => 88
[description] => message for user rkg uid 88
[assignee] => 88
[parent_id] =>
[cc] =>
[bcc] =>
[status] => 0
)
[1] => stdClass Object
(
[user_title] => Mr
[user_firstname] => Richard
[user_lastname] => Knight-Gregson
[assignee_title] => Mr
[assignee_firstname] => Richard
[assignee_lastname] => Knight-Gregson
[created] => 2015-03-26 12:45:47
[id] => 71
[user_id] => 88
[description] => This is child
[assignee] => 88
[parent_id] => 61
[cc] =>
[bcc] =>
[status] => 0
)
[2] => stdClass Object
(
[user_title] => Mr
[user_firstname] => Ted
[user_lastname] => Chiles
[assignee_title] => Mr
[assignee_firstname] => Richard
[assignee_lastname] => Knight-Gregson
[created] => 2015-03-27 10:11:56
[id] => 207
[user_id] => 47
[description] => cc 88
[assignee] => 88
[parent_id] =>
[cc] => 88
[bcc] => 112
[status] => 0
)
[3] => stdClass Object
(
[user_title] => Mr
[user_firstname] => Richard
[user_lastname] => Knight-Gregson
[assignee_title] => Mr
[assignee_firstname] => Richard
[assignee_lastname] => Knight-Gregson
[created] => 2015-03-27 10:17:31
[id] => 209
[user_id] => 88
[description] => sadfasdfasd
[assignee] => 88
[parent_id] =>
[cc] => 88
[bcc] => 0
[status] => 0
)
)
Here is the code I have at the moment to loop through the array, what I need to add to this is to get all elements that have a parent_id and then display them under their repsective parent in a list...
<table class="notifications-table" border="1">
<tr>
<th>S No.</th><th>Date</th><th>Employee</th><th id="details">Details</th><th>Assignee</th><th>Action</th>
</tr>
<?php foreach($notifications as $row){ ?>
<?php foreach($row as $k){
} ?>
<tr <?php if($row->status){ echo "class='resolved'"; } ?> id="row-<?=$row->id;?>">
<td><?=$row->user_id?></td><td><?=date('d M, H:i',strtotime($row->created));?></td>
<td><?=$row->user_title.' '.$row->user_firstname.' '.$row->user_lastname;?></td>
<td>
row id is : <?=$row->id.' == '.$row->parent_id; ?>
<?php //echo $row->id.' == '.$row->parent_id; ?>
<?=$row->description; ?><span data-parent-id="<?=$row->id;?>" data-user-id="<?=$row->user_id;?>" id="add_not" data-featherlight="#send_child_message" data-id="add_child_notification" class="glyphicon glyphicon-plus"></span>
</td>
<td><?=$row->assignee_title.' '.$row->assignee_firstname.' '.$row->assignee_lastname;?></td>
<td><input <?php if($row->status){ echo "disabled"; } ?> value="<?=$row->id;?>" data-action="not" type="checkbox" /></td>
</tr>
<?php } ?>
</table>
I have tried a few things but just cant get what I want!
Regards!
The code you have seems correct. I was able to take most of your structure and iterate over it with and got what you see in screenshot:
I was able to see 2 rows of info because I only used 2 elements (not all of them).
Ok, I see now what you are trying to do. You want to display details of the parent id element - which in the example, would be my "row 2" since row id 71 is a 'child of' row id 61.
If my assumption is correct, you need to associate the elements with each other based on this idea of parent & child.
Before your "Details" closing td, you can add...
<?php foreach($notifications as $row2){ ?>
<?php if ($row2->id == $row->parent_id) : ?> PARENT DESC: <?= $row2->description; ?><?php endif; ?>
<?php } ?>
Which should now let you pull in some parent property values.
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;
}
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>";
I've got a function in my model:
public function get_job($lsnumber = FALSE) {
$this->db->join('administrator', 'job.idadministrator = administrator.idadministrator');
$this->db->join('artwork', 'job.idjob = artwork.idjob');
if($lsnumber === FALSE) {
$query = $this->db->get('job');
return $query->result_array();
}
}
Returning this lets me generate a row for each entry in the database using a foreach loop in my view.
Sometimes these rows will have things in common, for example the idjob field as referenced in the join rule.
At the moment, I'm getting an output (from print_r) like this:
Array
(
[idjob] => 1
[lsnumber] => 12345
[custname] => Scott Brown (Customer)
[custemail] => sbrown#example.com
[custcompany] => Customer
[idadministrator] => 1
[complete] => 0
[administratorname] => Scott Brown (Administrator)
[administratoremail] => scott#example.com
[administratorjob] => Job
[administratorphone] => 01234 567890
[idartwork] => 1
[filename] => gb-usb1.jpg
[productname] => Bespoke USB Drive
[revision] => 0
[status] => N
)
Array
(
[idjob] => 1
[lsnumber] => 12345
[custname] => Scott Brown (Customer)
[custemail] => sbrown#example.com
[custcompany] => LSi (Customer)
[idadministrator] => 1
[complete] => 0
[administratorname] => Scott Brown (Administrator)
[administratoremail] => scott#example.com
[administratorjob] => Job
[administratorphone] => 01234 567890
[idartwork] => 2
[filename] => pa17.jpg
[productname] => Notebooks
[revision] => 0
[status] => Y
)
However, I'd like the array to be grouped and multidimensional, something like this:
Array
(
[idjob] => 1
[lsnumber] => 12345
[custname] => Scott Brown (Customer)
[custemail] => sbrown#example.com
[custcompany] => Customer
[idadministrator] => 1
[complete] => 0
[administratorname] => Scott Brown (Administrator)
[administratoremail] => scott#example.com
[administratorjob] => Job
[administratorphone] => 01234 567890
[artwork][0] => Array
(
[idartwork] => 1
[filename] => gb-usb1.jpg
[productname] => Bespoke USB Drive
[revision] => 0
[status] => N
)
[artwork][1] => Array
(
[idartwork] => 2
[filename] => pa17.jpg
[productname] => Notebooks
[revision] => 0
[status] => Y
)
)
I want to be able to group it by the idjob and build a sub-array of all the artworks joined to it.
I've tried all kinds of thing: array_chunk(), group by, all sorts.
Try this, you may have to change it slightly:
function get_job(){
$data = array();
$data = $this->db->get('job')->result_array();
foreach( $data as $key=>$each ){
$data[$key] = $this->db->where('idadministrator', $each['idadministrator'])->get('administrator')->row_array();
$data[$key]['artwork'] = $this->db->where('idjob', $each['idjob'])->get('artwork')->result_array();
}
return $data;
}