在PHP中从JSON数组中提取特定键值[关闭]

I have the following response from a payment gateway (JSON):

    {
  "response": {
    "token": "ch_lfUYEBK14zotCTykezJkfg",
    "success": true,
    "amount": 400,
    "currency": null,
    "description": "test charge",
    "email": "user@user.com",
    "ip_address": "203.192.1.172",
    "created_at": "2012-06-20T03:10:49Z",
    "status_message": "Success!",
    "error_message": null,
    "card": {
      "token": "card_nytGw7koRg23EEp9NTmz9w",
      "display_number": "XXXX-XXXX-XXXX-0000",
      "scheme": "master",
      "address_line1": "42 Sevenoaks St",
      "address_line2": null,
      "address_city": "Lathlain",
      "address_postcode": "6454",
      "address_state": "WA",
      "address_country": "Australia"
    },
    "transfer": null
  }
}

I'm trying to get the success => true part in an if statement like so:

<?php
    if($response['success'] == true) {
     // continue transaction
    }
?>

Without any luck, so I'm asking for some help on how I achieve this. It would be useful to be able to extract other key values too.

Thanks

The reason you aren't able to json_decode($response) is because $response is an object, not a JSON string.

The Pin-PHP library will automatically decode all requests for you, as per https://github.com/noetix/pin-php/blob/master/src/Pin/Handler.php#L87

To see if the response has been successful, use the response object as an object:

if ($response->response->success) {
    echo "Success!";
} else {
    echo "Failed :(";
}

Update

Your $response is already an object, therefore this expression should work:

if ($response->response->success == true) {
    // etc
}

Are you just looking for code that decodes the string representation? If so:

$response = <<<'EOM'
{
  "response": {
    "token": "ch_lfUYEBK14zotCTykezJkfg",
    "success": true,
    "amount": 400,
    "currency": null,
    "description": "test charge",
    "email": "user@user.com",
    "ip_address": "203.192.1.172",
    "created_at": "2012-06-20T03:10:49Z",
    "status_message": "Success!",
    "error_message": null,
    "card": {
      "token": "card_nytGw7koRg23EEp9NTmz9w",
      "display_number": "XXXX-XXXX-XXXX-0000",
      "scheme": "master",
      "address_line1": "42 Sevenoaks St",
      "address_line2": null,
      "address_city": "Lathlain",
      "address_postcode": "6454",
      "address_state": "WA",
      "address_country": "Australia"
    },
    "transfer": null
  }
}
EOM;

$responseData = json_decode($responseText, true);

if ($responseData['response']['success'] == true) {
 // continue transaction
}

Why not just use a json object like:

$jsonobject = json_encode($responseText);
$response = $jsonobject->response->success;
if($response === true) {
    // code here
}