2016-11-12 33 views
0

由於用戶從API輸入有不同的結果,因此我需要打印消息,指出沒有特定元素的結果並打印出其中的結果。例如,我想說,這個變量沒有結果:$ model = $ jfo - > engine-> valve-> timing; 這裏是我的代碼,因此遠低於這裏是鏈接到API: http://api.edmunds.com/api/vehicle/v2/vins/1GCGG25U261243927?fmt=json&api_key=2jwwaax2sc4kuq7vg7ud79rc如何將在PHP中發現的特定數據返回給JSON調用

<?php 

//ini_set("display_errors",1); 

//exit; 

$datvin=""; 
$title=""; 
$posts=""; 
$mds=""; 
$model=""; 
if (isset($_POST['vin'])){ 
$datvin=trim($_POST['vin']); 
$json_file = file_get_contents('http://api.edmunds.com/api/vehicle/v2/vins/'.$datvin.'?fmt=json&api_key=2jwwaax2sc4kuq7vg7ud79rc'); 
// convert the string to a json object 
$jfo = json_decode($json_file); 
if ($jfo != '' && $jfo !== null) { 
// read the title value 
$title = $jfo->make->name; 
// copy the posts array to a php var 
$posts = $jfo->make->id; 
$mds = $jfo->years[0]->year; 
$model = $jfo ->engine->valve->timing; 


}else { 

    $model="not found"; 
} 


} 


?> 
<form role="form" action="index.php" method="post"> 
      <div class="form-group"> 
       <label for="VIN" class="hidden-lg hidden-md">Enter your VIN</label> 
       <input type="text" class="form-control" id="VIN" name="vin" placeholder="Enter your VIN" required="required"> 
      </div> 

      <button type="submit" class="btn btn-primary btn-centered"><i class="fa fa-search"></i> Test VIN</button> 
     </form> 

     <div><?php echo $model; ?></div> 
+0

這是什麼線迴歸「$模式= $ JFO - >引擎 - >閥 - >時間;」 ? – azdonald

+0

我需要PHP腳本來打印沒有結果的行。 – fredcampbell

回答

0
<?php 

//ini_set("display_errors",1); 

//exit; 

$datvin=""; 
$title=""; 
$posts=""; 
$mds=""; 
$model=""; 
if (isset($_POST['vin'])){ 
$datvin=trim($_POST['vin']); 
@$str = file_get_contents('http://api.edmunds.com/api/vehicle/v2/vins/'.$datvin.'?fmt=json&api_key=2jwwaax2sc4kuq7vg7ud79rc'); 
// convert the string to a json object 
$json = json_decode($str, true); 

//echo count($json); 
//key to search 
$json['vin']; 
//show results 
if($_POST['vin'] ==$json['vin']){ 
     echo "Model is here!"; 
     echo $json['make']['id']; 
     echo $json['make']['name']; 
     echo $json['make']['niceName']; 
     echo $json['categories']['market']; 
     echo $json['model']['id']; 
     echo $json['model']['name']; 
     echo $json['model']['niceName']; 
    } 
    else { 

     $model="Model not found"; 
    } 
} 
+0

我的問題解決方案是$ json ['key'];如果在註釋中有更多元素,則會有一個count(數組);如果你需要循環更多的元素。 (Y) –

+0

這並沒有解決問題,如果我添加到列表某些元素不存在特定的VIN。也許最好是循環遍歷JSON中的所有元素,而不用在PHP文件中命名它們? – fredcampbell

+0

如果不存在添加到條件if($ _POST ['vin'] ==「」).. –

相關問題