I need to tidy up an array. And gather all similar information together.
This is going to be a huge order that I'm bringing to the table, however, it's well beyond my skill set and I've been trying to fix it for 3 days.
The message comes from a webservice, which i have absolutely no control over the output/response.
I need to be able to put all the info
But the following (i know its big sorry) is the SOAP object reply: (this has been reduced as well) eek.
[0] => RoomInformation Object
(
[Details] => DetailsType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-12
[AvailabilityStatus] => AvailableForSale
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[RoomId] => 1860
[RoomNo] => THAH01
[Description] => Hotel Alpha
)
)
)
[1] => RoomInformation Object
(
[Details] => DetailsType Object
(
[RoomRate] => RoomRateType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-12
[AvailabilityStatus] => AvailableForSale
)
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[RoomId] => 1861
[RoomNo] => THAH02
[Description] => Hotel Alpha
)
)
)
[2] => RoomInformation Object
(
[Details] => DetailsType Object
(
[RoomRate] => RoomRateType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-12
[AvailabilityStatus] => AvailableForSale
)
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[Amenities] => stdClass Object
(
)
[Configurations] => stdClass Object
(
)
[RoomId] => 1226
[RoomNo] => DENM01
[Description] => Hotel Beta
)
)
)
[3] => RoomInformation Object
(
[Details] => DetailsType Object
(
[RoomRate] => RoomRateType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-12
[AvailabilityStatus] => AvailableForSale
)
[MoreRatesExistInd] =>
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[Amenities] => stdClass Object
(
)
[Configurations] => stdClass Object
(
)
[RoomId] => 1227
[RoomNo] => DENM02
[Description] => Hotel Beta
)
)
)
[4] => RoomInformation Object
(
[Details] => DetailsType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-13
[AvailabilityStatus] => AvailableForSale
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[RoomId] => 1860
[RoomNo] => THAH01
[Description] => Hotel Alpha
)
)
)
[5] => RoomInformation Object
(
[Details] => DetailsType Object
(
[RoomRate] => RoomRateType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-13
[AvailabilityStatus] => AvailableForSale
)
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[RoomId] => 1861
[RoomNo] => THAH02
[Description] => Hotel Alpha
)
)
)
[2] => RoomInformation Object
(
[Details] => DetailsType Object
(
[RoomRate] => RoomRateType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-13
[AvailabilityStatus] => AvailableForSale
)
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[Amenities] => stdClass Object
(
)
[Configurations] => stdClass Object
(
)
[RoomId] => 1226
[RoomNo] => DENM01
[Description] => Hotel Beta
)
)
)
[3] => RoomInformation Object
(
[Details] => DetailsType Object
(
[RoomRate] => RoomRateType Object
(
[Total] => TotalType Object
(
[AmountAfterTax] => 1.00
)
[EffectiveDate] => 2011-08-13
[AvailabilityStatus] => AvailableForSale
)
[MoreRatesExistInd] =>
)
[RoomInformationExtend] => TPA_ExtensionsType Object
(
[RoomDetails] => RoomDetails Object
(
[Amenities] => stdClass Object
(
)
[Configurations] => stdClass Object
(
)
[RoomId] => 1227
[RoomNo] => DENM02
[Description] => Hotel Beta
)
)
)
TL;DR
Each hotel has 2 rooms with ids. Each of these 2 id's are seperated by dates, but are in the different parts of the array :(
[Hotel A]
HotelA RoomId = 01
Date = 12-08-2011
[Hotel A]
HotelA RoomId = 02
Date = 12-08-2011
[Hotel B]
HotelB RoomId = 01
Date = 12-08-2011
[Hotel B]
HotelB RoomId = 02
Date = 12-08-2011
[Hotel A]
HotelA RoomId = 01
Date = 13-08-2011
[Hotel A]
HotelA RoomId = 02
Date = 13-08-2011
[Hotel B]
HotelB RoomId = 01
Date = 13-08-2011
[Hotel B]
HotelB RoomId = 02
Date = 13-08-2011
I want to be able to put them into an array as such:
[Hotel A]
HotelA RoomId = 01
Date 12-08-2011
Date 13-08-2011
HotelA RoomId = 02
Date 12-08-2011
Date 13-08-2011
etc
Please help. I've been pulling my hair out :(
Here is an example of what ive tried:
$hotelinfo = array();
$k=0;
for($i = 0; $i < count($result->RoomInformation); $i++)
{
$flag = false;
$HotelObj = $result->RoomInformation[$i];
$HotelName = $result->RoomInformation[$i]->RoomInformationExtend->RoomDetails->Description;
$HotelId = $result->RoomStays->RoomStay[$i]->RoomInformation->RoomDetails->RoomId;
//$hotelinfo[$i][$HotelName] = array();
$hotelinfo[count($hotelinfo)] = array();
$hotelinfo[count($hotelinfo)][$HotelName] = array();
for($c = 0; $c < count($result->RoomInformation); $c++)
{
$thishotelObj = $result->RRoomInformation[$c];
$thisHotelName = $thishotelObj->RoomInformationExtend->RoomDetails->Description;
$thisHotelId = $thishotelObj->TPA_Extensions->RoomDetails->RoomId;
if($thisHotelName == $HotelName & $thisHotelId == $HotelId){
$hotelinfo[$i][$HotelName][$c] = $HotelName;
$hotelinfo[$i][$HotelName][$c] = $thisHotelName;
$i++;
}
}
}
was i even going in thr correct direction with this?
I suppose such a foreach loop would be sufficient. PHP doesn't check the existence of array members on updating, so it would just add the needed keys.
$HotelRooms = array();
$foreach($result as $r)
{
$HotelName = $r->RoomInformationExtend->RoomDetails->Description;
$HotelRooms[$HotelName][$r->RoomInformationExtend->RoomDetails->RoomId][] = $r->Details->EffectiveDate
}
When you do this...
$hotelinfo[count($hotelinfo)] = array();
$hotelinfo[count($hotelinfo)][$HotelName] = array();
You're actually adding two elements to $hotelinfo. For instance, if there were 4 elements in it already, the first line would set index 4, which is a new index (the existing ones are 0, 1, 2, and 3), thus adding an element.
Now that the first line is done, the number of elements in $hotelinfo is 5, and thus the second line sets index 5 - but index 5 corresponds to the next empty slot, and thus a second element is added (for an end result of indices 0-5 being set, with 4 and 5 both new).
Judging from your code, I don't think this is what you intended.
Going the extra mile (or two)...
I think what you might want to do first is get the data into a more usable format - grouped first by hotel, and then by room ID. So, let's do that:
$hotelInfo = array();
foreach($result->RoomInformation as $roomInfo) {
$hotelName = $roomInfo->RoomInformationExtend->RoomDetails->Description;
if(!isset($hotelInfo[$hotelName])) {
$hotelInfo[$hotelName] = array();
}
$thisHotel = $hotelInfo[$hotelName];
$roomId = $roomInfo->RoomInformationExtend->RoomDetails->RoomId;
if(!isset($thisHotel[$roomId])) {
$thisHotel[$roomId] = array();
}
$thisRoom = $thisHotel[$roomId];
Okay, so now we have a $thisRoom object that we can fill in info for. If a different item in the list we're going through already created an object for a particular hotel+room combination, we just get that already-created one instead of making a new one.
Now, we'll add any relevant information is the current item of data to our room object:
if(isset($roomInfo->Details)) {
if(isset($roomInfo->Details->EffectiveDate)) {
// "$foo[] = bar" appends 'bar' to the array '$foo'
$thisRoom[] = $roomInfo->Details->EffectiveDate;
}
if(isset($roomInfo->Details->RoomRate)) {
if(isset($roomInfo->Details->RoomRate->EffectiveDate)) {
$thisRoom[] = $roomInfo->Details->RoomRate->EffectiveDate;
}
}
}
}
After you've done this, you'll wind up with a structure in $hotelInfo that looks like this:
array(
['Hotel Alpha'] => array(
[1860] => array('2011-08-12', '2011-08-13'),
[1861] => array('2011-08-12', '2011-08-13')
),
['Hotel Beta'] => array(
[1226] => array('2011-08-12', '2011-08-13'),
[1227] => array('2011-08-12', '2011-08-13')
)
)
Which should be much easier to work with, and a lot closer to what you seem to be wanting.
Related
I am getting below json data thru Shiprocket API. Now I want to extract value of below variables in PHP code from this json.
I have tried to use json_decode but it did not work and show null value:
$data = json_decode($json);
$sr_status = $data['shipment_status'];
Please suggest the code to retrieve below variables value.
shipment_status , awb_code , courier_company_id
Array
(
[0] => stdClass Object
(
[tracking_data] => stdClass Object
(
[track_status] => 1
[shipment_status] => 7
[shipment_track] => Array
(
[0] => stdClass Object
(
[id] => 180339484
[awb_code] => 11150911492
[courier_company_id] => 55
[shipment_id] => 1711169662
[order_id] => 233223781187
[pickup_date] => 2023-01-11 03:02:00
[delivered_date] => 2023-01-16 12:22:00
[weight] => 0.25
[packages] => 1
[current_status] => Delivered
[delivered_to] => Solapur
[destination] => Solapur
[consignee_name] => ABC
[origin] => Ludhiana
[courier_agent_details] =>
[edd] =>
)
)
[shipment_track_activities] => Array
(
[0] => stdClass Object
(
[date] => 2023-01-16 12:22:00
[status] => 000-T-DL
[activity] => SHIPMENT DELIVERED
[location] => SOLAPUR
[sr-status] => 7
[sr-status-label] => DELIVERED
)
[1] => stdClass Object
(
[date] => 2023-01-16 11:34:00
[status] => 002-S-UD
[activity] => SHIPMENT OUTSCAN
[location] => SOLAPUR
[sr-status] => 17
[sr-status-label] => OUT FOR DELIVERY
)
)
[track_url] => https://shiprocket.co//tracking/11150911492
[etd] => 2023-01-14 17:02:00
[qc_response] => stdClass Object
(
[qc_image] =>
[qc_failed_reason] =>
)
)
)
)
you can try this:
$array = ...; // Your array here
$data= json_decode($array);
$shipment_status = $data[0]->tracking_data->shipment_status;
$awb_code = $data[0]->tracking_data->shipment_track[0]->awb_code;
$courier_company_id = $data[0]->tracking_data->shipment_track[0]->courier_company_id;
Or use $data = json_decode($json,true); which return an array where you can use
foreach($data as $val) {
$shipment_status = $val['tracking_data']['shipment_status'];
foreach ($val['shipment_track'] as $value) {
$awb_code = $value['awb_code'];
$courier_company_id = $value['courier_company_id'];
}
}
I have an array that is full of IDs that will match corresponding IDs in a separate array which is larger in terms of indices. I would like to first search through the larger array using the IDs from the smaller array and eliminate any indices that do not appear in the smaller array, and then place values present in the arrays that do match in my initial, smaller array. I have tried various nested for loops (come close, but does not get me there) but I can't seem to wrap my head about some array problems in general.
First array will look something like this:
Array
(
[0] => Array
(
[roleID] => 5b6468a500277c71b98405b1f140991c
[name] =>
[description] =>
[rate] =>
[hours] =>
[total] =>
)
[1] => Array
(
[roleID] => 5b6468a500277c74f6b2c065436b7d17
[name] =>
[description] =>
[rate] =>
[hours] =>
[total] =>
)
[2] => Array
(
[roleID] => 5b6468a500277c7697ba21928129e3af
[name] =>
[description] =>
[rate] =>
[hours] =>
[total] =>
)
)
Second array will look something like this
Array
(
[0] => stdClass Object
(
[ID] => 5b6468a500277c71b98405b1f140991c
[name] => CED
[objCode] => ROLE
[description] => CED
)
[1] => stdClass Object
(
[ID] => 5b6468a500277c74f6b2c065436b7d17
[name] => AD
[objCode] => ROLE
[description] => AD
)
[2] => stdClass Object
(
[ID] => 5b6468a500277c7697ba21928129e3af
[name] => AMG
[objCode] => ROLE
[description] => AMG
)
[3] => stdClass Object
(
[ID] => 5b6468a500277c77071c32c0bb2bae04
[name] => AP
[objCode] => ROLE
[description] => AP
)
[4] => stdClass Object
(
[ID] => 5b6468a500277c787e9680625c74ca80
[name] => AST
[objCode] => ROLE
[description] => AST
)
[5] => stdClass Object
(
[ID] => 5b6468a500277c79c0eddb8c14cc9f83
[name] => ASV
[objCode] => ROLE
[description] => ASV
)
)
I want to match the roleID in the first ID with the ID in the second array, then take the 'name' and 'description' keys and put it in the first array in the position it belongs. I have gotten close with the below code, but either a bunch of the arrays get misordered, or the 'name' and 'description' fields are the exact same for every index.
$projectUserRoleIDs = $client->get('project', $myProjectName, array('projectUserRoles:roleID'));
$projectUserRoleIDs = $projectUserRoleIDs->projectUserRoles;
$roleIDs = [];
for($a = 0; $a < count($projectUserRoleIDs); $a++)
{
$roleIDs[$a]['roleID'] = $projectUserRoleIDs[$a]->roleID;
// Get array of entire list of roles that are available in Workfront
// The roles:name category has all of the acronyms for each role, which can appear in an invoice
// The roles:description category has all of the full length names
$projectRoles = $client->get('project', $myProjectName, array('roles:name', 'roles:description'));
$projectRoles = $projectRoles->roles;
$roleLoop = [];
for($b = 0; $b < count($projectUserRoleIDs); $b++)
{
$roleLoop[] = $projectUserRoleIDs[$b]->roleID;
}
foreach($roleLoop as $key => $value) {
for($x = 0; $x<count($projectRoles); $x++)
{
if($projectRoles[$x]->ID === $value)
{
$name = $projectRoles[$x]->name;
$description = $projectRoles[$x]->description;
$roleIDs[$x]['name'] = $name;
$roleIDs[$x]['description'] = $description;
}
}
}
$roleIDs[$a]['rate'] = '';
$roleIDs[$a]['hours'] = '';
$roleIDs[$a]['total'] = '';
}
In the end I want my first array to look like this
Array
(
[0] => Array
(
[roleID] => 5b6468a500277c71b98405b1f140991c
[name] => CED
[description] => CED
[rate] =>
[hours] =>
[total] =>
)
[1] => Array
(
[roleID] => 5b6468a500277c74f6b2c065436b7d17
[name] => AD
[description] => AD
[rate] =>
[hours] =>
[total] =>
)
And so on... any help is appreciated and thank you.
I have a sample object array as a variable $xmlobj
SimpleXMLElement Object(
[SearchId] => 10769920113727_1556288871357_170040
[Categories] => SimpleXMLElement Object
(
[#attributes] => Array
(
[total_subcategories] => 1
)
[SubCategory] => SimpleXMLElement Object
(
[Title] => Reproductor MP3 y Multimedia
[Value] => 122701
[NumberOfProducts] => 1
)
)
[Products] => SimpleXMLElement Object
(
[#attributes] => Array
(
[totalResultsAvailable] => 1
[firstResultPosition] => 1
[totalResultsReturned] => 1
[currency] => EUR
[totalMerchantsAvailable] => 1
[searchOperator] => and
)
[Product] => SimpleXMLElement Object
(
[Offer] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => f94af9ec5186b53051c9ccf083ebddec
[type] => MANUFACTURER_PRODUCTS
)
[Title] => Apple iPod Nano 6 8 GB Gris
[Description] => iPod Nano 6 8 GB - Gris
[LastModified] => 2019-04-26 01:10:56
[MobileFriendly] => false
[Merchant] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 15348713
)
[Name] => Backmarket
)
[Price] => SimpleXMLElement Object
(
[#attributes] => Array
(
[currency] => EUR
)
[Price] => 99.99
[DeliveryCost] => 19.9
[DeliveryCostDetails] => SimpleXMLElement Object
(
[DeliveryCost] => 19.9
)
[TotalPrice] => 119.89
[PriceWithoutRebate] => 190
[Rebate] => 47
)
[ProductClass] => 2
[Availability] => 1
[DeliveryTime] => 24H / 4 días laborables
[Promo] => SimpleXMLElement Object
(
)
[OffensiveContent] => false
[FinancingOption] => SimpleXMLElement Object
(
)
[MerchantCategory] => Alta Tecnología Imágenes y sonidos Reproductor de MP3 Y MP4
[Brand] => Apple
[BrandId] => 211
[GreenProduct] => false
)
)
)
Now when I want to access e.g. price i do it like this:
$product_total_price = $xmlobj->Products->Product->Offer->Price->TotalPrice;
And it's OK - I get what I want, but I am having issue when I want "dynamically" to change what I am looking for like:
$search_part = "Products->Product->Offer->Price->TotalPrice";
$product_total_price = $xmlobj->$search_part;
I obviously get nothing... even when I try:
$product_total_price = $xmlobj."->".$search_part;
So my question is... how to do it ? :)
Thanks !
You will have to construct the path by exploding into an array, then looping to get each property.
For example...
$searchPart = "Products->Product->Offer->Price->TotalPrice";
$searchPath = explode('->', $searchPart);
$current = $xmlobj;
foreach ($searchPath as $segment) {
$current = $current->$segment;
}
var_dump($current);
or you can convert it to an array and then you will be able to get your attributes
$xml = simplexml_load_string($xmlobj);
$json = json_encode($xml);
$arr = json_decode($json,TRUE);
$parseString = 'Products->Product->Offer->Price->#attributes->currency';
$parsePath = explode('->', $parseString);
$current = $arr;
foreach ($parsePath as $segment) {
$current = $current[$segment];
}
var_dump($current);
You can take a look at eval that take your code as a string and evaluates it, but I strongly discourage its usage because it's a potentially (and very big) security hole.
Instead you could use explode passing as first argument -> and then loop over the resulting array to get the value you need:
$search_part = "Products->Product->Offer->Price->TotalPrice";
$chunks = explode("->", $search_part);
foreach ($chunks as $chunk) {
$temp = $xmlobj[$chunk];
}
$product_total_price = $temp;
or something similar, and then you will get you price dynamically
Note that if $xmlObj is of type Object you will need to use $xmlObj->{$chunk} instead of $xmlobj[$chunk]
I'm working on a website that displays properties. I have a huge XML feed in which I put into an array.
function search_results($department = '', $post_code = '', $min_price = '', $max_price = '', $type = '', $bedrooms = '') {
foreach($this->xml->property as $property) {
if($property->department == $department) {
$this->properties[] = $property;
}
}
$this->filter_results();
}
this first filters the XML based on the department such as 'For Sale' or 'To Rent'. I want to now be able to search this array based on the variables I pass though the function. For example:
if($this->properties->regionID == $post_code) {
$this->properties[] = $property;
}
But this doesn't work. This will be in a class called Results. How will I go about searching the array. I had a look at using array_filter(); but I couldn't get it working it would return Array() when I print_r it.
Does anyone know how to search/filter an array?
This is what the array looks like when I print_r:
Array ( [0] => SimpleXMLElement Object ( [propertyID] => 1 [branchID] => 1 [clientName] => Name [branchName] => Branch [department] => Lettings [referenceNumber] => 1 [addressName] => 4 [addressNumber] => SimpleXMLElement Object ( ) [addressStreet] => address [address2] => address2 [address3] => address3 [address4] => SimpleXMLElement Object ( ) [addressPostcode] => postcode [country] => postcode [displayAddress] => address [propertyBedrooms] => 1 [propertyBathrooms] => 1 [propertyEnsuites] => 0 [propertyReceptionRooms] => 1 [propertyKitchens] => 1 [displayPropertyType] => Flat/Apartment [propertyType] => 2 [propertyStyle] => 16 [propertyAge] => 0 [floorArea] => 0.00 [floorAreaUnits] => sq ft [propertyFeature1] => Converted School House [propertyFeature2] => City Centre Location [propertyFeature3] => Modern Fittings [propertyFeature4] => SimpleXMLElement Object ( ) [propertyFeature5] => SimpleXMLElement Object ( ) [propertyFeature6] => SimpleXMLElement Object ( ) [propertyFeature7] => SimpleXMLElement Object ( ) [propertyFeature8] => SimpleXMLElement Object ( ) [propertyFeature9] => SimpleXMLElement Object ( ) [propertyFeature10] => SimpleXMLElement Object ( ) [rent] => 525 [rentFrequency] => 1 [toLetPOA] => 0 [studentProperty] => SimpleXMLElement Object ( ) [availability] => 2 [mainSummary] => summary. [fullDescription] => SimpleXMLElement Object ( ) [dateLastModified] => 2014-05-02 [featuredProperty] => 0 [regionID] => 27 [latitude] => SimpleXMLElement Object ( ) [longitude] => SimpleXMLElement Object ( ) [flags] => SimpleXMLElement Object ( ) [images] => SimpleXMLElement Object ( [image] => Array ( [0] => image [1] => image [2] => image [3] => image [4] => image ) ))
Does anyone know how I would be able to search this query for example
$post_code = 43; $min_price = 300; $max_price = 500
and so on.
Looking at the code, the logic seems good to me.
There is something though that might cause the issue.
On line 4 of your code, you have:
$this->properties[] = $property;
It means that you have an array of properties.
But then, you are trying to access the object directly:
if($this->properties->regionID == $post_code) {
$this->properties[] = $property;
}
This looks strange to me. You are trying to see if an abject has the property you want, and then save the same object as it is an array.
So I guess, once you have built your $this->properties array, you just have to loop through it and apply your filters to return an array of properties with just what you are looking for:
foreach($this->properties as $singleProperty)
{
if($singleProperty->regionID == $post_code)
{
$this->foundProperties[] = $singleProperty;
}
}
A print_r of my object ($results) returns the following:
QueryResult Object
( [queryLocator] => [done] => 1 [records] =>
Array ( [0] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0167 [Partner_Research_Name__c] => MM Sample Organization-TBR Partner 2011 [Id] => a0V80000003FwjjEAC ) [Id] => a0V80000003FwjjEAC )
[1] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0170 [Partner_Research_Name__c] => Kansas City, Missouri Public Schools-TBR Partner 2011 [Id] => a0V80000003Fxf9EAC ) [Id] => a0V80000003Fxf9EAC )
[2] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0169 [Partner_Research_Name__c] => Newark Public Schools-TBR Partner 2011 [Id] => a0V80000003FxQ2EAK ) [Id] => a0V80000003FxQ2EAK )
[3] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0168 [Partner_Research_Name__c] => Breakthrough Charter Schools-TBR Partner 2011 [Id] => a0V80000003FxPxEAK ) [Id] => a0V80000003FxPxEAK )
[4] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0004 [Partner_Research_Name__c] => KIPP, San Antonio-TBR Partner 2011 [Id] => a0V80000003FrBUEA0 ) [Id] => a0V80000003FrBUEA0 )
[5] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0003 [Partner_Research_Name__c] => KIPP, Chicago - Gary-TBR Partner 2011 [Id] => a0V80000003FrB5EAK ) [Id] => a0V80000003FrB5EAK )
[6] => SObject Object ( [type] => Partner_Research__c [fields] => stdClass Object ( [Partner_Research_URL__c] => http://www.forms.com/184320?tfa_PRID=PR-0023 [Partner_Research_Name__c] => Harlem Village Academies-TBR Partner 2011 [Id] => a0V80000003FrEOEA0 ) [Id] => a0V80000003FrEOEA0 ) ) [size] => 7 )
I want to use a loop similar to the what is shown below to display a series of results however the foreach statement is incorrect.
foreach ($results as $result)
{
$id = $result[fields][Id];
$name = $result[fields][Partner_Research_Name__c];
$url = $result[fields][Partner_Research_URL__c];
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
What changes do I need to make to the foreach statement to get my code back on track?
What helps me in problems like this is to try to print inside the foreach loop. For example, you can do a var_dump of each $result and see what that structure is, and it could help determine how to proceed.
Here is how I eventually did it, thanks for the help provided by contributors.
foreach ($results->records as $result)
{
$id = $result->fields->Id;
$name = $result->fields->Partner_Research_Name__c;
$url = $result->fields->Partner_Research_URL__c;
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
$results is the name of the QueryResults object, I don't know what the real name in your code is.
foreach ($results->records as $result)
{
$id = $result->Id;
$name = $result->fields->Partner_Research_Name__c;
$url = $result->fields->Partner_Research_URL__c;
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
If I'm reading your sample correctly, your items are std objects instead of arrays. You may need to reference them like this:
foreach ($results as $result)
{
$id = $result->fields->Id;
$name = $result->fields->Partner_Research_Name__c;
$url = $result->fields->Partner_Research_URL__c;
$html .= "<tr><td>$id</td><td>$name</td><td>$url</td></tr>";
}
Your print_r sample above is difficult to read. If you could provide it with the indentation it would be helpful.