首页 > 解决方案 > 如何在多维 JSON 字符串中包含变量?

问题描述

我正在尝试在多维 JSON 字符串中包含一个变量。我想我需要使用 json_encode 但我不知道该怎么做。

$clientID = 123456;
$body = "<h1 id='heading1'>This is just a standard html message.</h1>";

curl_setopt($ch, CURLOPT_POSTFIELDS, "{
    \"subject\": \"How Did We Do\",
    \"clientId\": $clientID,
    \"assignedUserId\": 2988,
    \"public\": false,
    \"activity\": [
    {
      \"public\": false,
      \"comment\": {
          \"body\": $body
      }
    }
    ]
}");

标签: phpjsoncurl

解决方案


您应该制作一个数组并用于json_encode()对其进行编码。

$array = [
    'subject' => 'How Did We Do',
    'clientId' => $clientID,
    'assignedUserId' => 2988,
    'public' => false,
    'activity' => [
        [
            'public' => false,
            'comment' => [
                'body' => $body
            ]
        ]
    ]
];

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($array));

推荐阅读