Reputation: 2846
I have some data being returned from an API that is in the following format:
string(15) "[email protected]"
bool(true)
string(7) "generic"
array(5) {
["server"]=>
string(19) "imap.mail.yahoo.com"
["username"]=>
string(15) "[email protected]"
["port"]=>
int(993)
["use_ssl"]=>
bool(true)
["oauth"]=>
bool(false)
}
array(0) {
}
When I am trying to parse this with a foreach
loop, it is unsuccessful. I am assuming this is due to the string(15)
, bool(true)
, and string(7)
pieces of data located above the actual array.
Here is my foreach
loop:
$results = array();
foreach ($Request->getResults() as $imapSettings) {
$results['server'] = $imapSettings['server'];
$results['username'] = $imapSettings['username'];
$results['port'] = $imapSettings['port'];
$results['use_ssl'] = $imapSettings['use_ssl'];
$results['oauth'] = $imapSettings['oauth'];
}
When I run the code above, I get the following error: Warning: Illegal string offset 'server' in
. And I believe this error is usually a sign that something is not an array.
So my question is how do I go about parsing this piece of data?
UPDATE:
Here is was var_dump($Request->getResults());
returns:
array(5) {
["email"]=>
string(15) "[email protected]"
["found"]=>
bool(true)
["type"]=>
string(7) "generic"
["imap"]=>
array(5) {
["server"]=>
string(19) "imap.mail.yahoo.com"
["username"]=>
string(15) "[email protected]"
["port"]=>
int(993)
["use_ssl"]=>
bool(true)
["oauth"]=>
bool(false)
}
["documentation"]=>
array(0) {
}
}
Upvotes: 0
Views: 83
Reputation: 3260
I think this is what you are trying to do:
$response = $Request->getResults();
$results['server'] = $response['imap']['server'];
$results['username'] = $response['imap']['username'];
$results['port'] = $response['imap']['port'];
$results['use_ssl'] = $response['imap']['use_ssl'];
$results['oauth'] = $response['imap']['oauth'];
You don't need to loop through the result - you can just pull out the information you need from the 'imap' array contained in the result.
Also you can do this more succinctly like this which will yield the same results:
$results = $response['imap'];
Upvotes: 1
Reputation: 7785
foreach is only applicable for array, so you should escape the other types :
$results = array();
foreach ($Request->getResults() as $imapSettings) {
if (!is_array($imapSettings)) {
// you can do other stuff for other type
continue;
}
$results['server'] = $imapSettings['server'];
$results['username'] = $imapSettings['username'];
$results['port'] = $imapSettings['port'];
$results['use_ssl'] = $imapSettings['use_ssl'];
$results['oauth'] = $imapSettings['oauth'];
}
Upvotes: 0