Reputation: 187
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
)
)
)
)
Upvotes: 4
Views: 5067
Reputation: 20473
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.
Upvotes: 7
Reputation: 3795
One way to rome..
$findInObject = function($obj,$property) use (&$findInObject){
if(is_object($obj)){
$obvar = get_object_vars($obj);
if(array_key_exists($property,$obvar)){
return $obvar[$property];
} else {
foreach($obvar as $var){
$result = $findInObject($var,$property);
if($result){
return $result;
}
}
}
}
return null;
};
$obj = new stdClass();
$obj->MyProp1 = new stdClass();
$obj->MyProp1b = new stdClass();
$obj->MyProp1->MyProp2 = 'myresult';
$obj->MyProp1->MyProp2b = 'myresultb';
print_r($findInObject($obj,'MyProp2'));//Result: myresult
print_r($findInObject($obj,'MyProp2b'));//Result: myresultb
//OR
print_r($findInObject($obj->MyProp1,'MyProp2b'));//Result: myresultb
Upvotes: 1
Reputation: 187
As its always in the same place i'll use this
property_exists($response->Items->Item->OfferSummary,'LowestNewPrice')
Upvotes: 0
Reputation: 1112
My solution:
strpos
to check if key exists if all You need is to check if it is present or use preg_match()
to search for pair key=>value
Upvotes: -1