2016-04-25 156 views
0

我想使這個JSON的細節dynamic.currently它的static.as一個例子,我想爲這些JSON聲明幾個PHP變量。分配JSON到PHP變量

這裏是我的代碼

$body = '{ 
    "outboundSMSMessageRequest": { 
    "address": [ 
     "tel:+9456654978" 
    ], 

    "senderAddress": "tel:+95623654978", 
    "outboundSMSTextMessage": { 
     "message": "Welcome to fgf Your Confirmation Code - " 
    }, 

    "clientCorrelator": "", 
    "receiptRequest": { 
     "notifyURL": "", 
     "callbackData": "" 
    }, 
    "senderName": "" 
    } 
}'; 

正如在這裏你可以看到JSON已宣佈到$ body.what我想要做的就是獨立的變量,如$消息,$地址,$ senderAddress和分配他們到$身體。我怎樣才能做到這一點?

+0

你可以將它們添加了'json'轉換爲'array'後加入做重新轉換爲再次得到JSON之後。 –

+0

爲json創建一個你需要的數組然後使用'json_encode' –

回答

2

初始JSON:

$body = '{ 
     "outboundSMSMessageRequest": { 
     "address": [ 
      "tel:+9456654978" 
     ], 

     "senderAddress": "tel:+95623654978", 
     "outboundSMSTextMessage": { 
      "message": "Welcome to fgf Your Confirmation Code - " 
     }, 

     "clientCorrelator": "", 
     "receiptRequest": { 
      "notifyURL": "", 
      "callbackData": "" 
     }, 
     "senderName": "" 
     } 
    }'; 

解碼JSON來陣列

我使用第二個參數爲真,因爲我需要數組作爲締合。

$arr = json_decode($body, true); 

現在,插入必要的值:

$arr['outboundSMSMessageRequest']['address'] = "tel:+1234567890"; 
$arr['outboundSMSMessageRequest']['senderAddress'] = "tel:+0987654321"; 

$arr['outboundSMSMessageRequest']['outboundSMSTextMessage']['message'] = "test message"; 

現在編碼陣列JSON

$body = json_encode($arr); 

輸出

print_r($body); 

結果

{"outboundSMSMessageRequest":{"address":"tel:+1234567890","senderAddress":"tel:+0987654321","outboundSMSTextMessage":{"message":"test message"},"clientCorrelator":"","receiptRequest":{"notifyURL":"","callbackData":""},"senderName":""}}