Reputation: 847
First of all: Yes i did check other answers but they sadly didn't do the trick.
So i'm currently working on a script that checks if an email exists in the database. So the database data is obtained through a webservice and with an input filter function the following JSON
object is returned:
{"customers":{"customer":{"lastname":"test","firstname":"login","email":"[email protected]"}}}
Now i would like to check if the email is filled in correctly. I'm using a foreach()
statement to compare the values but i'm always getting a not found
returned. Maybe someone here is able to find the mistake i've made. So the full code is shown down below.
$resultEmail = ($webService->get( $optUser ));
$emailResult = json_encode($resultEmail);
$emailArray = json_decode($resultEmail);
echo ($emailResult);
echo ($chopEmail);
foreach($emailArray->customers->customer as $item)
{
if($item->email == $email)
{
echo "found it!";
}
}
// The $optUser is the JSON object
Upvotes: 0
Views: 45
Reputation: 51
It seems your mistake come from the foreach loop. You should write it this way :
foreach($emailArray->customers as $customer) {
if($customer->email == $email) {
echo "found it!";
}
}
Please note that $emailArray is not an array but an object when you don't set the second parameter of the json_decode function :
$obj = json_decode($data);
$array = json_decode($data,true);
Upvotes: 0
Reputation: 1398
The easiest way to do this would probably be to decode the string as an associative array instead of a json object, and then check if the key email
exists using the array_key_exists
function.
// passing true to json_decode will make it return an array
$emailArray = json_decode($resultEmail, true);
foreach($emailArray['customers'] as $customer) {
if(array_key_exists('email', $customer)) {
echo 'Found it!';
}
}
Upvotes: 0