[英]Search through a json array obtained from a database
首先:是的,我確實檢查了其他答案,但可悲的是他們沒有解決問題。
所以我目前正在研究一個腳本,該腳本檢查數據庫中是否存在電子郵件。 因此,通過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
最快的方法可能是strpos函數,因此您可以以這種方式使用它
function hasEmail($string, $email)
{
return strpos($string, $email) !== false;
}
//example
echo hasEmail($resultEmail, $email) ? 'Has email' : 'Email not found';
最簡單的方法可能是將字符串解碼為關聯數組而不是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!';
}
}
看來您的錯誤來自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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.