搜索从数据库中获取的json数组

时间:2017-11-30 12:53:10

标签: php arrays json

首先:是的,我确实检查了其他答案,但他们遗憾地没有做到这一点。

所以我正在开发一个脚本,用于检查数据库中是否存在电子邮件。因此,数据库数据是通过Web服务获得的,并且通过输入过滤器函数返回以下JSON对象:

{"customers":{"customer":{"lastname":"test","firstname":"login","email":"nielsvanenckevort@hotmail.com"}}} 

现在我想检查电子邮件是否填写正确。我正在使用foreach()语句来比较值,但我总是返回not found。也许这里的某个人能够找到我犯过的错误。所以完整的代码如下所示。

$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

3 个答案:

答案 0 :(得分:1)

可能最快的方式是strpos功能,所以你可以这样使用

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

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

答案 1 :(得分:0)

最简单的方法可能是将字符串解码为关联数组而不是json对象,然后使用array_key_exists函数检查密钥email是否存在。

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

答案 2 :(得分:0)

看来你的错误来自foreach循环。你应该这样写:

foreach($emailArray->customers as $customer) {
    if($customer->email == $email) {
        echo "found it!";
    }
}

请注意,当您没有设置json_decode函数的第二个参数时,$ emailArray不是数组,而是一个对象:

$obj = json_decode($data);
$array = json_decode($data,true);