簡體   English   中英

通過多維數組生成JSON

[英]Generating JSON via multi-dimensional array

我需要通過在 PHP 中將它們拉到一起來重新創建它:

 {
  "content": [
    {
      "type": "text/plain",
      "value": " "
    }
  ],
  "from": {
    "email": "dx@sendgrid.com",
    "name": "Ryan Smith"
  },
  "personalizations": [
    {
      "to": [
        {
          "email": "elmer@sendgrid.com"
        }
      ]
    }
  ],
  "subject": "my subject"
}

這就是我所擁有的,但它並不完全正確:

$content ='some long string';
$to =array('email'=>'elmer@sendgrid.com');

$objectArray = array(
    'content'=> array ('type'=>'text/html', 'value'=>$content),
    'from'=>array('from'=>'dx@sendgrid.com','name'=>'Ryan Smith'),
    'subject'=>'my subject',
    'personalizations'=> array('to'=>$to)
    );
$postfields = json_encode($objectArray);

編輯

抱歉點擊得太早了。

這是返回的錯誤:

{
    "errors": [
        {
            "message": "Invalid type. Expected: array, given: object.",
            "field": "content",
            "help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.content"
        },
        {
            "message": "Invalid type. Expected: array, given: object.",
            "field": "personalizations",
            "help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Personalizations-Errors"
        }
    ]
}

我在這里做錯了什么?

content屬性是一個 arrays 數組,因為您可能需要發送多個內容類型(即text/plaintext/html )。 personalizations也是如此。

'content' => [
    [
        'type' => 'text/plain',
        'value' => $textContent
    ],

    // ...
],
'personalizations' = [
    [
        'to' => [
            [
                'email' => $email,
                'name' =>  $name
            ]
        ],
        'subject' => $subject
    ],

    // ...
];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM