将Json分配给php变量

时间:2016-04-25 04:43:32

标签: php json

我想让这个json详细介绍dynamic.currently它的static.as一个例子我想为这些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声明了。我想做的是制作单独的变量,如$ message,$ address,$ senderAddress,并将它们分配给$ body。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

初始Json:

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

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

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

将json解码为数组

我使用第二个参数为true,因为我需要将数组作为关联。

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