在 json php 循环中查找变量



我需要在 php 的 json 数组中找到一个电话号码。 我正在尝试每个,但问题是如果找不到电话号码,我会得到多条记录。无论如何要写其他的,所以我只得到 1 个响应。如果找不到电话,我需要回发,但它为每个未找到的记录创建一个记录。

我的回答是这样的

未找到

未找到

发现

未找到

未找到

我需要 1 找不到不是多个元组。

$curl = curl_init();
$usertype='x-cw-usertype: integrator';
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_URL, "/apis/3.0/company/contacts");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: basic ' . base64_encode($username . ':' . $password),
'clientId: ',
$usertype,
'Content-type: application/json'
));
$response = curl_exec($curl);
curl_close($curl);
$json_contacts = json_decode($response, true);
//var_dump($json_contacts);
}
// Loop through Array
foreach ( $json_contacts  as $item ) { 

// If a phone number is found 
if ( $item['defaultPhoneNbr'] == '5551212' ) {  
echo 'found <br>';
} 
// If phone is not found
else if  ( $item['defaultPhoneNbr'] != '5551212' ){ 

echo 'Not found <br>';
} 
}

创建用于存储结果的变量。喜欢:

foreach ( $json_contacts  as $item ) { 
// Check item and the return value of  
// reset() function is equal then it  
// will be the first iteration 
if ( $item['defaultPhoneNbr'] == '6102070035' ) { 
// Desplay the array element 
$result = “found”;
break;
} 

// Check if item and return value of  
// end() function is equal then it 
// will be last iteration 
else if  ( $item['defaultPhoneNbr'] != '6102070035' ){ 

$result = “not found”;
} 
}

然后只是回应它。

echo $result;

最新更新