2016-09-15 102 views
0

我正在使用一個API來檢索法國公司的信息並輸出該信息的自定義JSON。您輸入公司名稱,並返回與搜索詞相匹配的所有公司信息。儘管這個系統並不是100%完美的,但它也帶來了很多與搜索價值幾乎匹配的公司。檢查一個字符串中是否有某些字符在PHP中

例如,我搜索'abc',並且在回報中我還獲得了名稱爲'abl'的公司。

所以我想在將它們放入結果數組之前將它們過濾掉。

public function transform($obj){ 

//The $obj is the information retrieved from the API in JSON. 
    $data = json_decode($obj, true); 
    $retval = array(); 

//The '$name = $data["params"]["name"];' is the name the API used as search parameter. 
    $name = $data["params"]["name"]; 

    foreach ($data["companies"] as $item){ 

//The '$item["names"]["best"]' is the name of the company. 
     if(strpos($item["names"]["best"], $name) !== false){ 
      $retval[] = [ 
      "Company name" => $item["names"]["best"], 
      "More info" => array(
       "Denomination" => $item["names"]["denomination"], 
       "Commercial name" => $item["names"]["commercial_name"] 
      ), 
      "Siren number" => $item["siren"], 
      "Street" => $item["address"], 
      "Zip code" => $item["postal_code"], 
      "City" => $item["city"], 
      "Vat_number" => $item["vat_number"], 
      "Established on" => $item["established_on"] 
      ]; 
     }    
    } 
    return json_encode($retval, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); 
} 

但即使在創建數組對象之前比較字符串,它仍會返回這些'錯誤'的公司。任何人對我做錯了什麼都有想法?任何幫助將不勝感激!

編輯:如果有人想知道我使用的API,這裏的鏈接:https://firmapi.com/

+0

這可以幫助你http://stackoverflow.com/questions/16283837/find-exact-string-inside-a-string – Farhan

回答

1

使用的preg_match()可以不用strpos找到精確匹配。希望這將幫助你

public function transform($obj){ 

//The $obj is the information retrieved from the API in JSON. 
    $data = json_decode($obj, true); 
    $retval = array(); 

//The '$name = $data["params"]["name"];' is the name the API used as search parameter. 
    $name = $data["params"]["name"]; 

    foreach ($data["companies"] as $item){ 

//The '$item["names"]["best"]' is the name of the company. 
     $string = 'Maramures'; 
     if (preg_match("~\b$string\b~",$name)) 
      $retval[] = [ 
      "Company name" => $item["names"]["best"], 
      "More info" => array(
       "Denomination" => $item["names"]["denomination"], 
       "Commercial name" => $item["names"]["commercial_name"] 
      ), 
      "Siren number" => $item["siren"], 
      "Street" => $item["address"], 
      "Zip code" => $item["postal_code"], 
      "City" => $item["city"], 
      "Vat_number" => $item["vat_number"], 
      "Established on" => $item["established_on"] 
      ]; 
     }    
    } 
    return json_encode($retval, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); 
} 
+0

謝謝!這工作完美! – RandomStranger

相關問題