I have an object being returned from an API and i need to see if a property exists. Problem is the properties could be other objects, each of which would need to be searched.
This is probably solved with recursion but i cant get my head around it or my code examples to work.
I'm amazed that i cant find a solution to this online so posting here for expert advice.
This is an example of an object, i need to make sure that "LowestNewPrice" exists and have the value returned
stdClass Object
(
[OperationRequest] => stdClass Object
(
[HTTPHeaders] => stdClass Object
(
[Header] => stdClass Object
(
[Name] => UserAgent
[Value] => PHP-SOAP/5.6.2
)
)
[RequestId] => 20bd3916-3d92-4519-b3be-c80c7cf16b1b
[Arguments] => stdClass Object
(
[Argument] => stdClass Object
(
[Name] => Service
[Value] => AWSECommerceService
)
)
[RequestProcessingTime] => 0.005986476
)
[Items] => stdClass Object
(
[Request] => stdClass Object
(
[IsValid] => True
[ItemLookupRequest] => stdClass Object
(
[IdType] => ASIN
[ItemId] => 1405278269
[ResponseGroup] => OfferSummary
[VariationPage] => All
)
)
[Item] => stdClass Object
(
[ASIN] => 1405278269
[OfferSummary] => stdClass Object
(
[LowestNewPrice] => stdClass Object
(
[Amount] => 44
[CurrencyCode] => GBP
[FormattedPrice] => £0.44
)
[LowestUsedPrice] => stdClass Object
(
[Amount] => 1
[CurrencyCode] => GBP
[FormattedPrice] => £0.01
)
[TotalNew] => 30
[TotalUsed] => 12
[TotalCollectible] => 0
[TotalRefurbished] => 0
)
)
)
)
You can use isset
for checking object property:
if(isset($response->Items->Item->OfferSummary->LowestNewPrice)) {
// LowestNewPrice exists
} else {
// Doesn't exist or one of the properties doesn't exist
}
This way, you don't need to check each property individually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With