[英]json_encode with object in array
我想创建一个WordPress的功能,通过卷曲使用JSON将数据发送到松弛网络挂接。 我更习惯于在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到松驰成功网络挂接:
{
"username": "Email Notifier",
"mrkdwn": true,
"icon_emoji": ":email:",
"text": "whatever" //generated by using PHP variables
}
现在,我希望能够在名为attachment
的数组中输出text
属性和其他属性,如下所示:
{
"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语法解决这个问题。 有任何想法吗?
像@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()的本节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.