微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用php从JSON解析值

我是PHP和JSON的新手,所以希望有人可以帮助我.

我有一个PHP,第三方执行POST,提供JSON数据.发送数据的一个例子是:

> {   "created": 1326853478,   "livemode": false,   "id":
> "evt_00000000000000",   "type": "charge.succeeded",   "object":
> "event",   "data": {
>     "object": {
>       "id": "ch_00000000000000",
>       "object": "charge",
>       "created": 1366838716,
>       "livemode": false,
>       "paid": true,
>       "amount": 1000,
>       "currency": "gbp",
>       "refunded": false,
>       "fee": 59,
>       "fee_details": [
>         {
>           "amount": 59,
>           "currency": "usd",
>           "type": "stripe_fee",
>           "description": "Stripe processing fees",
>           "application": null,
>           "amount_refunded": 0
>         }
>       ],
>       "card": {
>         "object": "card",
>         "last4": "4242",
>         "type": "Visa",
>         "exp_month": 2,
>         "exp_year": 2016,
>         "fingerprint": "cniJDyeew54ashW6Iyr",
>         "country": "US",
>         "name": "wibble3",
>         "address_line1": null,
>         "address_line2": null,
>         "address_city": null,
>         "address_state": null,
>         "address_zip": null,
>         "address_country": null,
>         "cvc_check": "pass",
>         "address_line1_check": null,
>         "address_zip_check": null
>       },
>       "captured": true,
>       "failure_message": null,
>       "amount_refunded": 0,
>       "customer": null,
>       "invoice": null,
>       "description": null,
>       "dispute": null
>     }   } }

我希望能够提取某些项目然后根据这些值进行处理.

使用此代码,我可以轻松地提取“类型”:

$body = @file_get_contents('PHP://input');
$event_json = json_decode($body);
print $event_json->{'type'};

但是我无法提取“费用”,例如,这似乎是我成功提取价值的地方,或者“描述”,这又是另一个等级.

我希望能够从这个JSON字符串中仅提取某些项目(例如,Type,Fee,Description,Last4),但我完全迷失了.我很欣赏这可能是一个相当基本的任务,但我没有在哪里.

任何帮助,感激不尽!

解决方法:

首先,我建议将true作为第二个参数传递给json_decode.这会产生关联数组而不是对象,这使得它更容易使用.

然后,你可以这样做:

$fee = $event_json['data']['object']['fee'];

您可以根据需要多次链接这些方括号,以深入研究数组.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐