想要在json中仅获取两个对象

时间:2018-10-24 05:23:33

标签: php json

我正在尝试使用以下代码进行代码验证。我已经查看了StackOverflow中的答案,但无法获得正确的结果。

代码工作正常,但我只想回显两个值。

validate.php 页面代码在此处:

if(isset($apKey) && isset($code))   {
    $en     = new En();
    $Key       = $apKey;
    $Codes = $code;

if($Key == null || $Codes == null)  {
    echo json_encode(['data' => 'No Key or code found, Please try again']);
    exit;
}  
  $response = $en->validate($Key,$Codes);
  $result = json_decode($response);
  $elements = json_encode(['data' => $result]); 
  echo $elements;
  exit;
}
  echo json_encode(['data' => 'No Key or code found, Please try again']);
  exit;

现在,我正在尝试使用以下代码检查此验证页结果:

$siteurl = urlencode($_SERVER['SERVER_NAME']);
    $arrContextOptions = array(
        "ssl" => array(
            "verify_peer" => false,
            "verify_peer_name" => false
        )
    );
    $file = file_get_contents('http://www.validates.com/validate.php?code=' . $check , false, stream_context_create($arrContextOptions));
    $checks = json_decode($file, true);
    $elements = $checks['data']; 
    echo print_r($elements);

结果如下:

Array
   ( 
     [buyer] => abcd 
    )

所以我想做什么。我只想在此代码后回显买家和错误消息:$checks = json_decode($file, true);

错误结果在这里:

{"data":{"error":404,"description":"No sale belonging to the current user found with that code"}}

例如:

if(buyer){echo 'true';}
if(error message){echo 'error';}

1 个答案:

答案 0 :(得分:1)

我想您可以用array_key_exists检查是否有错误。您可以执行以下操作:

$checks = json_decode($file, true);
$data = $checks['data']; 
if (array_key_exists("error", $data))
    echo $data["description"];
else 
    echo $data["buyer"];