使用PHP数组和循环创建有效的JSON

时间:2018-06-20 12:11:02

标签: php mysql json

我搞砸了FB Messenger,并试图发回“列表”,必须使用mySQL查找和循环来创建它。

在Facebook开发人员here上定义了要发送回的正确JSON。

我不明白的是,用PHP如何创建对象的“页眉”和“页脚”,我做了一个循环,使用数据库结果将主要内容放入数组中:

$messagePayload = array();
while($row = $result->fetch_assoc()) {
    $messagePayloadC = array();
    $messagePayloadC['title'] = $row['Name'].";
    $messagePayloadC['item_url'] = $row['link'];
    $messagePayloadC['image_url'] = $row['Image'];
    $messagePayloadC['subtitle'] = "$".$row['Price'].";
    $messagePayloadC['buttons']['type'] = "web_url";
    $messagePayloadC['buttons']['url'] = $row['link'];
    $messagePayloadC['buttons']['title'] = "Go!";
    $messagePayload[] = $messagePayloadC;
}

echo var_dump(json_encode($messagePayload))."<p>";

我需要做的是在开头和结尾处添加所有缺少的香料。我的数组输出为:

{"title":"My Television","item_url":"https:\/\/www.google.com\/","image_url":"product-image.jpg","subtitle":"$5","buttons":{"type":"web_url","url":"https:\/\/www.google.com\/","title":"Go!"}}

例如缺少的标头是:

"attachment": {
  "type": "template",
  "payload": {
    "template_type": "list",
    "top_element_style": "compact",
    "elements": [

我会以错误的方式处理吗?

0 个答案:

没有答案