问题
I am currently working within the campaign monitor api.
Here is my code:
require_once '../../csrest_general.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxx');
$wrap = new CS_REST_General($auth);
$result = $wrap->get_clients();
echo "Result of /api/v3/clients\n<br />";
if($result->was_successful()) {
echo "Got clients\n<br /><pre>";
var_dump($result->response);
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
}
echo '</pre>';
This outputs the following:
array(2) {
[0]=>
object(stdClass)#5 (2) {
["ClientID"]=>
string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
["Name"]=>
string(12) "xxxxxxxxxxxx"
}
[1]=>
object(stdClass)#6 (2) {
["ClientID"]=>
string(32) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
["Name"]=>
string(15) "xxxxxxxxxxxx"
}
}
How do i go about putting this into a foreach loop? when i try the following:
foreach ($result as $result->response) {
echo $result;
}
i get this error:
Catchable fatal error: Object of class CS_REST_Wrapper_Result could not be converted to string
回答1:
Credit to Mark Butler for answering this, so I've added his solution:
foreach($result->response as $entry) { echo $entry->ClientID; }
In general terms, getting at the contents of Campaign Monitor results requires you to access the response->Results part of the object returned from the method. Unfortunately, this is not clear from the API or documentation which tends to just 'print_var' the objects returned from the method calls.
For example, listing subscribers in a list:
require_once '/csrest_lists.php';
$sList = new CS_REST_Lists(YOUR_CM_LIST_ID,YOUR_CM_ACCT_KEY);
$sSubscribers = $sList->get_active_subscribers()->response->Results; // return results
foreach($sSubscribers as $s) {
echo $s->EmailAddress . "\t" . $s->Name . "\t" . $s->State . "\n";
}
Hope this is useful to people - thanks danyo for the question - there are few of these on SO at the moment. Pete
来源:https://stackoverflow.com/questions/17531151/stdclass-object-and-foreach-loops-campaign-monitor-api