手动创建的JSON字符串无效

bd1hkmkf  于 4个月前  发布在  其他
关注(0)|答案(1)|浏览(55)

我创建了一个手动循环来形成一个JSON,它被我正在启动的一个项目上的另一个API使用,请在下面找到。
问题是API无法识别我的JSON输出。我检查了循环的结果,它看起来很好。
如果我直接复制并粘贴我的结果(echo),它可以正常工作,但是通过我的循环,它就不工作了。有人知道吗?

foreach ($array['hits'] as $key => $value) {

    $message = $message.'{
            "title":"'.$value['Title'].'",
            "image_url":"'.$value['image'].'",
            "subtitle":"'.substr($value['Detail'],0,120).'",
            "buttons":[
                    {
                            "type":"web_url",
                            "url":"'.SITE_ROOT_URL.$value['URL'].'?utm_source=chatbot",
                            "title":"Leia mais"
                    }
            ]
    },';

}

$message = '{"messages": [
             {
                     "attachment":{
                             "type":"template",
                             "payload":{
                                     "template_type":"generic",
                                     "elements":['.rtrim($message,",").']
                             }
                     }
             }
     ]
}';

echo $message;

字符串
var_export($array 'hits'])的输出如下所示:

array ( 0 => array ( 'ID' => '69', 'Title' => 'This is an example', 'URL' => 'example/1', 'Detail' => 'Some description here...', 'image' => 'image1.png', 'objectID' => '75877631') ), 1 => array ....

e0bqpujr

e0bqpujr1#

不要手工生成JSON。构建数组,然后使用json_encode()

$messages = array();
foreach ($array['hits'] as $key => $value) {
    $messages[] = array(
        'title' => $value['Title'],
        'image_url' => $value['image'],
        'subtitle' => substr($value['Detail'], 0, 120),
        'buttons' => array(
            array(
                'type' => 'web_url', 
                'url' => SITE_ROOT_URL.$value['URL'].'?utm_source=chatbot', 
                'title' => "Leia mais"
            )
        )
    );
}
$result = array(
    'messages' => array(
        'attachment' => array(
            'type' => 'template',
            'payload' => array(
                'template_type' => 'generic',
                'elements' => $messages
            )
        )
    )
);
echo json_encode($result);

字符串
DEMO
注意你手工构造的JSON数组和对象的元素是如何直接Map到PHP数组的。如果JSON包含:

{ "something": "something else" }


对应的PHP是:

array("something" => "something else")

相关问题