在json php循环中查找变量

问题描述 投票:0回答:1

我需要使用php在json数组中找到电话号码。我正在尝试foreach,但问题是,如果找不到电话号码,我会获得多个记录。无论如何有写其他,所以我只能得到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>';

} 
}
php json search
1个回答
0
投票

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

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;
© www.soinside.com 2019 - 2024. All rights reserved.