PHP Json格式变量声明

时间:2017-04-18 06:45:07

标签: php json

我使用paypal api获取收款人信息 我得到了json的结果。如何获取emailfirst_namelast_name不同的变量

以下是JSON结果:

{
    id: "PAY-4L2624428H450980CLD23F4A",
    intent: "sale",
    state: "approved",
    cart: "74345738MA858411Y",
    payer: {
        payment_method: "paypal",
        status: "VERIFIED",
        payer_info: {
            email: "haj.mohamed-facilitator@pmgasia.com",
            first_name: "test",
            last_name: "facilitator",
            payer_id: "Z2ZSX2WM9ALD2",
            shipping_address: {
                recipient_name: "test facilitator"
            },
            country_code: "SG"
        }
    }
}

3 个答案:

答案 0 :(得分:1)

使用json_decode并使用foreach循环,您将获得具有键和值的所有数据。

  $json = "{id: "PAY-4L2624428H450980CLD23F4A",intent: "sale",state: "approved",cart: "74345738MA858411Y",
   payer: {payment_method: "paypal",status: "VERIFIED",payer_info: {email: "haj.mohamed-facilitator@pmgasia.com",first_name: 
   "test",last_name: "facilitator",payer_id: "Z2ZSX2WM9ALD2",shipping_address: {recipient_name: "test facilitator"},country_code: "SG"}}";

 $temp = json_encode($json);

 foreach ($temp as $key=>$value) 
 {
 // $key and  $value
 }

答案 1 :(得分:0)

您必须将json字符串解码为对象或数组。如果您的结果是$json_str变量,那么

$result_arr= json_decode($json_str, true) // returns in array
$result_obj= json_decode($json_str) // returns in object

了解更多详情http://php.net/manual/en/function.json-decode.php

答案 2 :(得分:0)

@Haj Mohamed首先你的json是无效的,因为密钥id,intent等都不是双引号,因此php json这个json无效,如果你json_decode($json_str, true)那么你会得到{{1}因此你必须安排这个json,如:

null