简体   繁体   中英

Search through a json array obtained from a database

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":"nielsvanenckevort@hotmail.com"}}} 

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

Probably the quickest way would be strpos function, so you can use it this way

function hasEmail($string, $email)
{
    return strpos($string, $email) !== false;
}

//example
echo hasEmail($resultEmail, $email) ? 'Has email' : 'Email not found';

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!';
    }
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM