json_encode与数组中的对象

时间:2018-01-10 15:04:18

标签: php arrays json object

我试图在Wordpress中创建一个函数,通过Curl将带有JSON的数据发送到Slack webhook。我更习惯于在JavaScript中构建数组和对象的方式,所以在PHP编码为JSON之前在PHP中执行此操作对我来说有点混乱。

这就是用于此编码的PHP的外观:

$data = json_encode(array(
     "username"=> "Email Notifier",
     "mrkdwn"=> true,
     "icon_emoji"=> ":email:",
     "text" => "*Name:* {$posted_data["your-name"]}\n*Email:* {$posted_data["your-email"]}\n*Subject:* {$posted_data["your-subject"]}\n*Message:*\n >{$posted_data["your-message"]}",
     ));

  // Finally send the data to Zapier or your other webhook endpoint
       $ch = curl_init("https://hooks.slack.com/services/Txxxxxx/Bxxxxxx/xxxxxxxxxxxxxxx"); // replace with your Zapier webook
       curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
       curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
       curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); //Optional timeout value
       curl_setopt($ch, CURLOPT_TIMEOUT, 5); //Optional timeout value
       $result = curl_exec($ch);
       curl_close($ch);

   return $result;

这会成功将以下JSON发送到Slack webhook:

{
   "username": "Email Notifier",
   "mrkdwn": true,
   "icon_emoji": ":email:",
   "text": "whatever" //generated by using PHP variables
}

我现在希望能够在名为text的数组中输出attachment属性和其他属性,如下所示:

{
   "username": "Email Notifier",
   "mrkdwn": true,
   "icon_emoji": ":email:",
   "text": "You have received a new message!",
   "attachment": [
      { 
         "text": "whatever", //generated by using PHP variables
         "fallback": "Required plain-text summary of the attachment.",
         "color": "#36a64f",
      }
   ]
}

但我不确定如何使用PHP语法解决这个问题。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

试试这个,就像@deceze说的那样。

$data = json_encode(array(
  "username"=> "Email Notifier",
  "mrkdwn"=> true,
  "icon_emoji"=> ":email:",
  "text" => "*Name:* {$posted_data["your-name"]}\n*Email:* {$posted_data["your-email"]}\n*Subject:* {$posted_data["your-subject"]}\n*Message:*\n >{$posted_data["your-message"]}",
  "attachment" => array(
    array( 
      "text" => "whatever",
      "fallback" => "Required plain-text summary of the attachment.",
      "color" => "#36a64f",
    ),
  ),
));

// Finally send the data to Zapier or your other webhook endpoint
    $ch = curl_init("https://hooks.slack.com/services/Txxxxxx/Bxxxxxx/xxxxxxxxxxxxxxx"); // replace with your Zapier webook
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); //Optional timeout value
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); //Optional timeout value
    $result = curl_exec($ch);
    curl_close($ch);

return $result;

另请参阅PHP官方文档json_encode()

上的这一部分