davidtsadler / ebay-sdk-php

An eBay SDK for PHP. Use the eBay API in your PHP projects.
Apache License 2.0
349 stars 341 forks source link

Cannot iterate over properties that are an array? #137

Closed ChangePlaces closed 7 years ago

ChangePlaces commented 7 years ago

I'm trying to parse the GeteBayDetails response and convert all the CountryDetails to an array:

$payload['countryDetails'] = array_walk($resp->CountryDetails, function($x){return $x->toArray();});

Except the first $x is actually the whole countrydetails array - it instead iterates over the 5 elements of CountryDetails object instead of through them, so I get the error that I'm calling toArray on an array.

How can I actually do what I want to do?

davidtsadler commented 7 years ago

CountryDetails is not a true array, but is "array like" in that it implements ArrayAccess, Countable, and Iterator.

For the most part you can treat it as a normally array. However, for some functions you need to first call iterator_to_array to convert it into a true array.

Also array_walk returns a boolean. I think you need to call array_map to get what you want.

$array = iterator_to_array($response->CountryDetails);
$results = array_map(function ($countryDetails) {
    return $countryDetails->toArray();
}, $array);

The above can also be reduced to a single line as the SDK supports JMESPath Expressions;

$results = $response->search('CountryDetails[]');
ChangePlaces commented 7 years ago

wow - excellent thanks. learn something new everyday!