2017-04-18 61 views
-1

我使用paypal api来获取收款人信息。
我得到了json结果。如何获得emailfirst_namelast_name不同的变量PHP Json格式变量声明

这里是JSON结果:

{ 
    id: "PAY-4L2624428H450980CLD23F4A", 
    intent: "sale", 
    state: "approved", 
    cart: "74345738MA858411Y", 
    payer: { 
     payment_method: "paypal", 
     status: "VERIFIED", 
     payer_info: { 
      email: "[email protected]", 
      first_name: "test", 
      last_name: "facilitator", 
      payer_id: "Z2ZSX2WM9ALD2", 
      shipping_address: { 
       recipient_name: "test facilitator" 
      }, 
      country_code: "SG" 
     } 
    } 
} 
+0

使用谷歌,你会发现PHP函数[json_decode()](http://php.net/manual/en/function.json-decode.php)如果第二个参数设置为“true”,则转换将返回JSON作为关联数组。 –

+0

鉴于json不是有效的json请检查[http://jsonviewer.stack.hu/] –

回答

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

1

使用json_decode和使用你会得到所有的密钥和值的数据使用foreach循环。

$json = "{id: "PAY-4L2624428H450980CLD23F4A",intent: "sale",state: "approved",cart: "74345738MA858411Y", 
    payer: {payment_method: "paypal",status: "VERIFIED",payer_info: {email: "[email protected]",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 
} 
0

@Haj穆罕默德的第一个所有JSON是无效的,因为密钥ID,意图等没有双引号,以便在PHP的角度来看,这JSON是无效的,如果你做json_decode($json_str, true)那么你会得到null值,你要安排此JSON,如:

<?php 
    $json_string = '{ 
        "id":"PAY-4L2624428H450980CLD23F4A", 
        "intent":"sale", 
        "state":"approved", 
        "cart":"74345738MA858411Y", 
        "payer":{ 
         "payment_method":"paypal", 
         "status":"VERIFIED", 
         "payer_info":{ 
         "email":"[email protected]", 
         "first_name":"test", 
         "last_name":"facilitator", 
         "payer_id":"Z2ZSX2WM9ALD2", 
         "shipping_address":{ 
          "recipient_name":"test facilitator" 
         }, 
         "country_code":"SG" 
         } 
        } 
       }'; 
    $infoArr = json_decode($json_string, true); 

    //1.Now you can use foreach(): 

        //or 2.you can directly get the value by array index like below; 
echo "email : ".$infoArr["payer"]["payer_info"]["email"]."<br>"; 
echo "first_name : ".$infoArr["payer"]["payer_info"]["first_name"]."<br>"; 
echo "last_name : ".$infoArr["payer"]["payer_info"]["last_name"]."<br>";