How to Separate PHP Object - php

I am confused on how to separate the following output into separate variables. Here is the array I am working with:
stdClass Object ( [FlightInfoExResult] => stdClass Object ( [next_offset] => 1 [flights] => stdClass Object ( [faFlightID] => UAL1-1489818347-airline-0169 [ident] => UAL1 [aircrafttype] => B789 [filed_ete] => 17:05:00 [filed_time] => 1489818347 [filed_departuretime] => 1490074200 [filed_airspeed_kts] => 430 [filed_airspeed_mach] => [filed_altitude] => 0 [route] => [actualdeparturetime] => 0 [estimatedarrivaltime] => 1490136300 [actualarrivaltime] => 0 [diverted] => [origin] => KSFO [destination] => WSSS [originName] => San Francisco Intl [originCity] => San Francisco, CA [destinationName] => Singapore Changi [destinationCity] => Singapore ) ) )
I am outputting this through the FlightAware API system. Here is the code I am using to output the above:
$params = array("ident" => "UAL1","howMany" => 1,"offset" => 0 );
$result = $client->FlightInfoEx($params);
print_r($result);
Here is an example of how I would like it to seperate the object:
UAL1,B789 ect.

First of all that's not an array your working with, it is an object.
To access it's properties use the -> syntax, i.e.
$flightInfoExResult = $result->FlightInfoExResult;
You can then access the next_offset property with
flightInfoExResult->next_offset; and so on.

Related

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

How to echo an array value

I am fairly new to PHP and I am writing a PHP function that grabs an object from SOAP.
I found a code to convert it to an array but I can't manage to echo any data.
The array from print_r
Array
(
[Status] => Array
(
[Code] => 0
[Message] => OK
)
[Order] => Array
(
[OrderNumber] => 9334543
[ExternalOrderNumber] =>
[OrderTime] => 2014-07-15T15:20:31+02:00
[PaymentMethod] => invoice
[PaymentStatus] => Paid
[ShipmentMethod] => Mypack
[DeliveryStatus] => Delivered
[Language] => sv
[Customer] => Array
(
[CustomerId] => 13556
[CustomerNumber] =>
[Username] => admin
[Approved] => 1
[OrgNumber] => 9309138445
[Company] =>
[VatNumber] =>
[FirstName] => Jane
[LastName] => Doe
[Address] => Gatan
[Address2] =>
[Zip] => 1230
[City] => Staden
[Country] => Sweden
[CountryCode] => SE
[PhoneDay] => 84848474
[PhoneNight] =>
[PhoneMobile] =>
[Email] => mail#msn.com
[NewsLetter] =>
[OrgType] => person
[OtherDelivAddress] =>
[DelivName] =>
[DelivAddress] =>
[DelivAddress2] =>
[DelivZip] =>
[DelivCity] =>
[DelivCountry] =>
[DelivCountryCode] =>
)
[Comment] =>
[Notes] => 9063025471 UK/MA
[CurrencyCode] => SEK
[ExchangeRate] => 1
[LanguagePath] => se
[FreightWithoutVat] => 0
[FreightWithVat] => 0
[FreightVatPercentage] => 25
[PayoptionFeeWithoutVat] => 0
[PayoptionFeeWithVat] => 0
[PayoptionFeeVatPercentage] => 25
[CodWithoutVat] => 0
[CodWithVat] => 0
[CodVatPercentage] => 0
[DiscountWithoutVat] => 0
[DiscountWithVat] => 0
[DiscountVat] => 0
[TotalWithoutVat] => 4388
[TotalWithVat] => 5485
[TotalVat] => 1097
[PayWithoutVat] =>
[AffiliateCode] =>
[AffiliateName] =>
[OrderField] => Array
(
[0] => Array
(
[Name] => external_ref
[Value] => 43445
)
[1] => Array
(
[Name] => webshopid
[Value] => 423
)
[2] => Array
(
[Name] => webshopname
[Value] => Manuell
)
)
)
)
Non working code
echo $array[1][0]
I have tried different combos of indexes. I know how to return the values from the soap object but if I could do it this way it would be easier. It should work shouldn't it?
$array[1] is the second index of the array. the key of this array us "Status", this array contains a code and message
i assume you want to echo the message, you can do that with the following
echo $array[1]["Status"]["Message"];
You should use $array['Status']['Code'] , $array['Status']['Message'], $array['Order']['OrderNumber'], $array['Order']['Customer']['CustomerId'] and so on to display your data. It's an associative array so you need to use string keys and not numbers
try
$array['Order']['Customer']['LastName']
is my best guess without losing my sanity in that one line.
But for us to be sure please post the print_r($array) output
There are some way I always do this:
print_r($array);
And the other way is
$array[0]['Order']['LastName']
Try to access the arrays elements with the string keys, not the integer ones you are using:
echo $array['Order']['Customer']['Address'];
Another way you could see what is going on is by iterating through the array, and print out the keys and values:
foreach ($array as $key => $value)
echo "Key=$key value=$value<br>";

How do I print the data within this nested stdClass Object?

I am attempting to print values within this nested stdClass Object but I'm having trouble accessing them. How do I print, for example, the value of "originCity"?
stdClass Object (
[FlightInfoResult] => stdClass Object (
[next_offset] => 1
[flights] => stdClass Object (
[ident] => SWA2558
[aircrafttype] => B737
[filed_ete] => 00:50:00
[filed_time] => 1362879561
[filed_departuretime] => 1362880080
[filed_airspeed_kts] => 442
[filed_airspeed_mach] =>
[filed_altitude] => 410
[route] => LBY MEI J31 VUZ
[actualdeparturetime] => 1362880080
[estimatedarrivaltime] => 1362882900
[actualarrivaltime] => 1362882600
[diverted] => [origin] => KMSY
[destination] => KBHM
[originName] => New Orleans Intl
[originCity] => New Orleans, LA
[destinationName] => Birmingham-Shuttlesworth Intl
[destinationCity] => Birmingham, AL
)
)
)
Try
$var->FlightInfoResult->flights->originCity
you can use
$object->FlightInfoResult->flights->originCity;
to access objects properties.
sorry about that.

how to display individual values?

I get this from print_r($data):
Array (
[0] => Array (
[0] => stdClass Object (
[cto_office_id] => 1
[office_name] => Airtel India
[address_line1] => Bendoor well
[phone_office1] => 12345678912
[phone_office2] => 789451234512
[address_line2] => Kankanady Circle
[city] => Mangluru
[state] => Haryana
[pin_code] => 002
[country] => India
[web_url] => airte.co.in
[office_quote] => Office
[date_registered] => 2011-11-24 05:59:51
[bill_mail_id] => 15612561
[bill_mail_id_type] =>
[acc_status] => enabled
[comments] =>
[is_account_deleted] => 0
[account_deleted_date] => 0000-00-00 00:00:00
)
)
)
I tried this $data['phone_office1'], but that does not work.
You have an object that is nested inside two arrays. You can get it out like this:
$data[0][0]->phone_office1

PHP SoapClient converting Array to String

Another SOAP question - I have a large multidimensional array, which echo's out fine when using print_r (eg you can see all of the data). The problem arises when I use
SOAPClient->__soapCall('Function', array('paramaters' => $feedUpload));
This actually returns an xml that looks like this: (using __getLastRequest)
<soap-env:envelope xmlns:ns1="http://www.property24.com/prosol/P24Feed" xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
<soap-env:body>
<ns1:uploadlistings>
<ns1:feedupload>
<ns1:version>1</ns1:version>
<ns1:usertoken>
<ns1:token>3c7b39ea-c10b-451f-95bf-5118d84fb089</ns1:token>
</ns1:usertoken>
<ns1:command>UPLOAD</ns1:command>
<ns1:compress>None</ns1:compress>
<ns1:listings>
<ns1:listing>
<ns1:listingnumber>361000001</ns1:listingnumber>
<ns1:propertycategory>SR</ns1:propertycategory>
<ns1:listingdata>Array</ns1:listingdata>
<ns1:listingtype>A</ns1:listingtype>
</ns1:listing>
</ns1:listings>
</ns1:feedupload>
</ns1:uploadlistings>
</soap-env:body>
</soap-env:envelope>
As you can see, for ListingData it returns "Array". Here is the array schema:
Array
(
[parameters] => Array
(
[FeedUpload] => Array
(
[Version] => 1
[UserToken] => Array
(
[Token] => 5ece25e7-77d9-4dbf-8b8f-e047759ab8f4
)
[Command] => UPLOAD
[Compress] => None
[Listings] => Array
(
[Listing] => Array
(
[PropertyCategory] => SR
[ListingNumber] => 361000001
[ListingType] => A
[ListingData] => Array
(
[MandateDetails] => Array
(
[ListingNumber] => 361000001
[ListingType] => A
[MandateType] => O
[ClosedUserGroup] => C
[MarketCode] => A
[ListPrice] => 111000
[OccupationDate] =>
[OffMarketDate] =>
[OnMarketSince] =>
[ExpiryDate] => 2011-07-13T09:56:14Z
[ListDate] => 2011-07-13T09:51:14Z
[UpdateDate] => 2011-07-13T09:51:14Z
[VirtualTourUrl] =>
[ActualDirections] =>
[ShowHouseDirection] =>
[ViewComments] =>
[InternetComments] => Excellent stand situated on the flood plane with large riverine trees and great mountain views. The estate is situated along the world renowned Blyde River and is 394 ha in extent with only 154 sites on 4000 square metres. The estate has an array of plains game such as antelope, giraffe and wildebeest as well as hippo and crocodile. The riverine flood plain provides great birding opportunities such as the Pels fishing owl. There is a restaurant and clubhouse that serves meals and cocktails and offers
)
[PropertyDetails] => Array
(
[PropertyCategory] => SR
[PropertyType] => SRX
[Status] => ACTV
[Province] => Eastern Cape
[Town] => Aberdeen
[Suburb] => Balvinie
[StreetName] => Test Street
[StreetNumber] => 5
[PostalCode] => 0123
[ErfSize] => 1200
[HouseSize] =>
[Age] =>
[OwnerType] => G
[VATRegistered] => false
[MunicipalRatesAndTaxes] => 0
[MunicipalImprovementsValue] => 0
[MunicipalLandValue] => 0
[MunicipalTotalValue] => 0
[StandNumber] =>
[StandNumberSubdivided] =>
[PortionNumber] =>
[OwnerShipType] =>
)
[ResidentialDetails] => Array
(
[NoOfBathrooms] => 2
[BathroomDescription] =>
[NoOfBedrooms] => 6
[BedroomDescription] =>
[NoOfKitchens] => 2
[KitchenDescription] =>
[NoOfReceptionRooms] => 2
[ReceptionRoomDescription] =>
[NoOfStudies] => 1
[StudiesDescription] =>
[NoOfDomesticBathrooms] => 2
[NoOfDomesticRooms] => 0
[DomesticRoomsDescription] =>
[NoOfGarages] => 0
[GarageDescription] =>
[NoOfOutsideToilets] => 0
[Coverage] => 0
[Pool] => false
[PoolDescription] =>
[Flatlet] =>
[FlatletDescription] =>
[FlatletSize] =>
[EstablishedGarden] =>
[OutBuildingSize] =>
[NoOfCarports] => 0
[CarportsDescription] =>
[ParkingBayNumber] =>
[Parking] =>
[ParkingDescription] =>
[BusinessRights] =>
[HeightRestrictions] =>
[CommonFeatures] =>
[NumberOfShares] =>
[FacingOptions] =>
[KitchenOptions] =>
[FeatureOptions] =>
[SpecialFeatureOptions] =>
[WallOptions] =>
[WindowOptions] =>
[StyleOptions] =>
[TemperatureControlOptions] =>
[SecurityOptions] =>
[RoofOptions] =>
[RoomOptions] =>
[PoolOptions] =>
[BathroomOptions] =>
)
[AgentDetails] => Array
(
[InternetAgentName] => Ricky Duckworth
[InternetAgentPhoneNumber] => 0157931534
[InternetAgentEmailAddress] => ricky#propertylogic.net
[InternetAgentSMSNumber] => 0796057834
[ListingAgentCode] => CN21
[ListingAgencyCode] => CWP021
)
)
)
)
)
)
)
As you can see the array is structured fine. It's like SoapRequest has got to far into an array and stopped. I also get the notice
Notice: Array to string conversion in /var/www/vhosts/propertylogic.net/httpdocs/soap_feed/property24/add_property.php on line 178
Which is the SOAPCall line.
Thanks very much!
EDIT
[EDIT]Ok, basically the SOAP server requested that section to be raw xml, so I had to replace the Array with a String - sort of stupid way of doing things, but the error message now makes sense! (Can't answer my own question).
You'd better generate and use WSDL to create SOAP Client and define complex types there. This way every SOAP type will be converted to PHP types in a natural way (in your example it'll be an array of objects).
Or you can replace array with string as you did already, though it is a dirty magic :)

Categories