【问题标题】:Find variable in json php loop在 json php 循环中查找变量
【发布时间】:2019-11-30 19:57:02
【问题描述】:

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

我的回复是这样的

找不到

找不到

找到

找不到

没有找到

我需要 1 Not found not multiple。

$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】:

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

    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;
    

    【讨论】:

    • 如果您不想继续循环,请使用“Break”。
    • 这似乎有效,不知道为什么,但我尝试了 break ealier,它似乎正在超时我的循环。我只是重做了代码,它似乎正在工作。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2014-05-27
    • 1970-01-01
    相关资源
    最近更新 更多