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"
        }
    }
}

使用json_decode并使用for for for foreach liap y y y y y y y y y y y y hou都将带有键和值。

  $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
 }

您必须将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

@haj mohamed您的第一个JSON无效,因为键ID,意图等不是两倍引用,因此,如果您做json_decode($json_str, true),那么此JSON无效,那么您将获取null值,因此您必须像以下方式安排此JSON:

<?php
  $json_string = '{
                   "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"
                      }
                   }
                }';
  $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>";

最新更新